【问题标题】:How to show error message in component.ts file?如何在 component.ts 文件中显示错误消息?
【发布时间】: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


【解决方案1】:

问题

问题是您正在检索数据表单 API 并订阅服务类本身。

修复

你可以做的是,让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
})

【讨论】:

    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 2017-01-02
    • 2013-02-05
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多