I'm new to Angular and hoping someone can guide me through the process of making a soap call. I can call the endpoint with a Request in SoapUI and it returns the correct Response. Now I'd like to know how to do the same thing in Angular.
The closest one I could find is Answer #3. But it doesn't provide enough context for a beginner.
Here's what I've got so far:
app.component.ts
import { Component } from '#angular/core';
import { SoapService } from './soap.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
title = 'Test of SOAP calls'
name = 'SOAP Prototype';
response: any;
constructor(private soapService: SoapService)
{
soapService.getResponse().subscribe(
res => {
console.log("returned data: ",res);
}
);
}
}
soap.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Subject } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
#Injectable()
export class SoapService
{
constructor(private httpClient: HttpClient) { }
getResponse()
{
const myheaders = new HttpHeaders();
myheaders.set('Content-Type','text/xml');
const myparams = new HttpParams();
myparams.set('username', 'me');
myparams.set('acctId','1585');
myparams.set('domain','USR');
myparams.set('active','true');
const response = this.httpClient.post<any>('url-to-soap-service', {headers: myheaders, params: myparams, responseType: 'text'});
console.log(response);
return response;
}
}
Nothing is logged to the console in app.component.ts, nor in soap.service.ts.
I'm see this error in the browser console:
"<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">soap:Bodysoap:Faultsoap:ClientError
reading XMLStreamReader: Unexpected character '{' (code 123) in
prolog; expected '<'\n at [row,col {unknown-source}]:
[1,1]</soap:Fault></soap:Body></soap:Envelope>"
I don't see how there can be an unexpected char when the HttpClient is generating the soap envelope.
What am I doing wrong?
Related
maybe someone can help me: I have created my first Angular package. The package itself has to provide different services to make HTTP requests to a server and return the results.
However, when importing the service, the web page stops rendering and I get an error message:
core.mjs:6484 ERROR Error: ASSERTION ERROR: token must be defined [Expected=> null != undefined <=Actual]
at throwError (core.mjs:326)
at assertDefined (core.mjs:322)
at bloomHashBitOrFactory (core.mjs:3591)
at getOrCreateInjectable (core.mjs:3379)
at Module.ɵɵdirectiveInject (core.mjs:14392)
at NodeInjectorFactory.AppComponent_Factory [as factory] (app.component.ts:10)
at getNodeInjectable (core.mjs:3556)
at instantiateRootComponent (core.mjs:10159)
at createRootComponent (core.mjs:12259)
at ComponentFactory.create (core.mjs:21580)
My Service:
// imports ...
/**
* DoctorService
*/
#Injectable({
providedIn: "root"
})
export class DoctorService {
constructor(private readonly httpClient: HttpClient) { }
/**
* Returns a doctor by a given uuid.
*
* #param uuid
* #return Promise<Doctor>
*/
public async getDoctorByUUID(uuid: string): Promise<Doctor> {
const uuidRegExp = new RegExp(/[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}/);
if (!uuidRegExp.test(uuid)) {
console.error("UUID does not have a valid format. It needs to be in a 8-4-4-4-12 digit pattern.")
return new Promise<Doctor>(() => {
return [];
});
}
const httpParams: HttpParams = new HttpParams();
httpParams.set("module", "mydoc");
httpParams.set("sektion", "show_doctor");
httpParams.set("uuid", uuid);
httpParams.set("return", "json");
const request = this.httpClient.get<Doctor>(API_BASE_URL, { params: httpParams });
return firstValueFrom(request);
}
}
Component which uses the Service:
import {Component} from '#angular/core';
import {DoctorService} from "my-doc-util/src/lib/services/doctor-service/doctor.service";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular-testing';
constructor(private readonly doctorService: DoctorService) {
}
}
I have experienced the same exact error (angular 11)
I don't know if it's the same reason but in my case, it turned out that the component had an uninitialized input.
I am following a tutorial on which we create an Angular service for sending emails from
a form using Mailthis Email API.
In the service code I get an error on the 'api' word that says
" Property 'api' does not exist on type 'MyService' ".
Any advice will be very helpfull!
My code is:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http:HttpClient
) { }
PostMessage(input:any){
return this.http.post(this.api, input, { responseType:'text' }).pipe(
map(
(response:any) => {
if(response){
return response;
}
},
(error:any) => {
return error;
}
)
)
}
}
I don't see anywhere you have defined api as a variable, i assume it is the endpoint you want to call, so you can define it as
api: string = "yourUrl";
This question already has answers here:
How do I return the response from an Observable/http/async call in angular?
(10 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am trying to populate MatTableDataSource using Http local call to JSON. But it's not working. I think the assignment operation in 'subscribe()' in 'data-table.component.ts' file is not working. I tried to debug and tried to find the solution, but nothing worked and most of the time I end up breaking up m code. Please help me.
Thanks
Below are the codes with respective file names:
data-table.component.ts
import { Component } from '#angular/core';
import { MatTableDataSource } from '#angular/material';
import { FormDataService } from 'src/app/services/form-data.service';
#Component({
selector: 'app-data-table',
templateUrl: './data-table.component.html',
styleUrls: ['./data-table.component.css']
})
export class DataTableComponent {
displayedColumns: string[] = ['request_number', 'request_name', 'last_updated_date', 'completion', 'status'];
ELEMENT_REQUEST = [];
constructor(private _formDataService: FormDataService) {
console.log("Before getting data: ", this.ELEMENT_REQUEST)
this._formDataService.getformData()
.subscribe((data:any) => {
this.ELEMENT_REQUEST = data; // This line not working!
console.log("Inside: ",data);
}, err => {
console.log(err);
})
console.log("After getting data: ", this.ELEMENT_REQUEST)
}
dataSource = new MatTableDataSource(this.ELEMENT_REQUEST);
logData(row) {
console.log(row);
}
applyFilter(filterValue: String) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
}
form-data-model.ts
export interface Form_Data {
request_name: string;
request_number: number;
last_updated_date: string;
completion: number;
status: string;
}
form-data.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Form_Data } from './form-data-model';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class FormDataService {
_url = "/assets/data/form_data.json"
constructor(private http: HttpClient) { }
getformData(): Observable<Form_Data[]> {
return this.http.get<Form_Data[]>(this._url);
}
}
I got this snippet from the chrome console.
Before getting Data is all good, Inside is also working, but After getting data, there is nothing in the array
Image
I am stuck at the phase of learning CRUD operation in Angular 5
I have been trying for hours but no avail, it seems i can't solve the error.
When I subscribe data which comes from service and try to insert data using push. It says undefined.
addtasks.component.ts
import { Component } from '#angular/core';
import { AddTaskService } from '../../services/add-task.service';
import { Tasks } from '../../../Tasks/Tasks';
#Component({
selector: 'app-addtasks',
templateUrl: './addtasks.component.html',
styleUrls: ['./addtasks.component.css']
})
export class AddtasksComponent {
tasks: Tasks[];
title: string;
constructor(private addTaskService: AddTaskService) {
console.log("Add tasks page has been accessed...");
}
addTasks(event){
event.preventDefault();
var newTask = {
title: this.title,
isDone: false
};
this.addTaskService.addTask(newTask).subscribe(task => {
this.tasks.push(task);
this.title = '';
});
}
}
add-task.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class AddTaskService {
constructor(private http: Http) { console.log("Add Task service initialized..."); }
addTask(newTask){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
console.log(newTask);
return this.http.post('http://localhost:2200/api/tasks', JSON.stringify(newTask), {headers: headers})
.map(res => res.json());
}
}
Model
Tasks.ts
export class Tasks {
title: string;
isDone: boolean;
}
The error showing in my console
TypeError columnNumber: 13 fileName:
"http://localhost:2200/main.bundle.js" lineNumber: 193 message:
"_this.tasks is undefined" stack:
"../../../../../src/app/components/addtasks/addtasks.component.ts/AddtasksComponent.prototype.addTasks/<#http://localhost:2200/main.bundle.js:193:13\n../../../../rxjs/_esm5/Subscriber.js/SafeSubscriber.prototype.tryOrUnsub#http://localhost:2200/vendor.bundle.js:1697:13\n../../../../rxjs/_esm5/Subscriber.js/SafeSubscriber.prototype.next#http://localhost:2200/vendor.bundle.js:1644:17\n../../../../rxjs/_esm5/Subscriber.js/Subscriber.prototype._next#http://localhost:2200/vendor.bundle.js:1585:9\n../../../../rxjs/_esm5/Subscriber.js/Subscriber.prototype.next#http://localhost:2200/vendor.bundle.js:1549:13\n../../../../rxjs/_esm5/operators/map.js/MapSubscriber.prototype._next#http://localhost:2200/vendor.bundle.js:4978:9\n../../../../rxjs/_esm5/Subscriber.js/Subscriber.prototype.next#http://localhost:2200/vendor.bundle.js:1549:13\nonLoad#http://localhost:2200/vendor.bundle.js:75626:21\n../../../../zone.js/dist/zone.js/http://localhost:2200/polyfills.bundle.js:2504:17\nonInvokeTask#http://localhost:2200/vendor.bundle.js:53623:24\n../../../../zone.js/dist/zone.js/http://localhost:2200/polyfills.bundle.js:2503:17\n../../../../zone.js/dist/zone.js/http://localhost:2200/polyfills.bundle.js:2271:28\n../../../../zone.js/dist/zone.js/http://localhost:2200/polyfills.bundle.js:2578:24\ninvokeTask#http://localhost:2200/polyfills.bundle.js:3619:9\nglobalZoneAwareCallback#http://localhost:2200/polyfills.bundle.js:3645:17\n"
__proto: Object { stack: "", … }
You should initialize tasks variable before using it.
Initialize it in the constructor function.
constructor(private addTaskService: AddTaskService) {
console.log("Add tasks page has been accessed...");
this.tasks = [];
}
That's why you have an error saying its undefined.
First of all, I am very new to Angular2 (or any other version actually) and I have followed several tutorials to get me started but I'm now in a dead end and I don't know how to proceed.
Here is the background: I am accessing a third party web API through a POST request (I did that in a service) and it returns HTML markup of the control I need to render on my page, so I made a component of it. It works fine (I had to create a custom pipe to work around the DOM sanitization though).
And here's my issue: in the markup I'm receiving from the web API there's JavaScript stuff to initialize the control that is supposed to execute as soon as it is on the page (it does in every other language I used this control in, PHP, Java, JavaScript, ASP.NET, etc) but for some reason, using Angular2 I can see the script in the DOM, properly inserted at the end of the markup but it does not execute so my control does not work.
Here is my component code:
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { MyService } from './my.service'
#Component({
selector: 'mycontrol',
template: `<div style="width:1200px; height:1000px;" [innerHtml]="htmlContent | keepHtml"></div>`,
styleUrls: ['app/control-min.css'],
encapsulation: ViewEncapsulation.None
})
export class MyComponent implements OnInit {
htmlContent: any;
constructor(private myService: MyService) {
}
ngOnInit(): void {
this.myService.getControlMarkup().subscribe(
response => this.htmlContent = response["HtmlContent"],
error => this.htmlContent = <any>error
);
}
}
And here is my service code:
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
#Injectable()
export class MyService {
headers: Headers;
options: RequestOptions;
constructor(private http: Http) {
this.headers = new Headers({ 'Content-Type': 'application/json' });
this.options = new RequestOptions({ headers: this.headers });
}
getControlMarkup() {
let controlConfig = {
SessionId: "mySessionId",
ControlId: "MyControl1"
};
let body = JSON.stringify(controlConfig);
return this.http
.post('http://localhost:62968/api/GetControl', body, this.options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
Any idea how I can make this work?