【发布时间】:2019-03-24 23:26:28
【问题描述】:
如何将错误消息发送到我的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);
})
}
【问题讨论】:
-
你在哪里订阅?
-
API Service ts 文件中的订阅方法
-
服务订阅应始终从组件发生。获取 httpResponse 后,您仍然可以在服务中进行映射和其他操作,但要获得干净的代码,请在组件内部进行订阅。这也有助于使用这些服务调用注册用户操作。例如,如果您需要在单击按钮时执行一些操作,您可以在组件中处理它并从那里进行服务调用。希望这能澄清一点。
标签: angular api angular6 angular2-services angular-services