如何在component.ts文件中显示错误消息?

时间:2018-10-20 06:30:08

标签: angular api angular6 angular2-services angular-services

如何将错误消息发送到我的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);
    })
  }

1 个答案:

答案 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
})