如何将错误消息发送到我的component.ts
文件中?
如何访问服务类错误消息以显示在HTML
页上?
Component.ts添加方法
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服务方法
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);
})
}
答案 0 :(得分:3)
问题是您正在检索数据表单API并订阅Service类本身。
您可以做的是,让Service类处理HTTP调用,并让组件通过订阅来处理它。
服务等级
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添加方法
addNew(): any { this.apiService.addIndexReference(Data.AccessToken,this.indexReference,this.indexId).subscribe(respone => {
console.log("Successfull saved"); //<-- SUCCESS
}, error => {
console.log("Error occured"); //<-- ERROR
})