Reputation: 188
How to get the error message to my component.ts
file?
How to access the service class error message to show on HTML
page?
Component.ts Add method
addNew(): any { this.apiService.addIndexReference(Data.AccessToken,this.indexReference,this.indexId,(result)=>{
//if Not success
//
//else
console.log("result"+ JSON.stringify(result));
this.indexReference.id=(result as IndexReference).id;
})
}
API service method
public addIndexReference(accessToken: any, body: IndexReference,id:number,action: any) {
return this.post<IndexReference>(environment.apiUrl + '/api/v1/indexes/'+id+ '/references', accessToken
, body
, action);
}
public post<T>(url: string, accessToken: string, body: T, action: any) {
let httpOptions = {
headers: new HttpHeaders({ 'Authorization': accessToken })
};
this.http.post(url, body, httpOptions).subscribe(respone => {
(respone) => this.booleanAddValue = false;
action(respone);
}, error => {
console.log(error);
return throwError(error);
})
}
Upvotes: 0
Views: 1392
Reputation: 11243
The problem is you are retrieving the data form API and subscribing in the Service class itself.
What you can do is, let the Service class handle HTTP call and let the component handle it by subscribing it.
Service class
public addIndexReference(accessToken: any, body: IndexReference,id:number,action: any) {
return this.post<IndexReference>(environment.apiUrl + '/api/v1/indexes/'+id+ '/references', accessToken
, body
, action);
}
public post<T>(url: string, accessToken: string, body: T, action: any) {
let httpOptions = {
headers: new HttpHeaders({ 'Authorization': accessToken })
};
return this.http.post(url, body, httpOptions); //It will return Observable
}
Component.ts Add method
addNew(): any { this.apiService.addIndexReference(Data.AccessToken,this.indexReference,this.indexId).subscribe(respone => {
console.log("Successfull saved"); //<-- SUCCESS
}, error => {
console.log("Error occured"); //<-- ERROR
})
Upvotes: 3