Angular2:HTTP Observables流程尚不清楚

时间:2016-11-16 12:26:46

标签: angular

在我的组件中,我正在调用Rest服务并希望保存数据,Rest调用不成功(预期行为),所以我希望执行此代码:

  

错误=> console.log(错误)&& this.accessLevel == AccessLevel.DISBLED

export class CustomerComponent extends SuperChildComponent{
  public static url:string='/orderViewCustomer/';
  public id;
  public allowed: boolean = false;
  public  accessLevel:AccessLevel =null;
  public componentname:string;
  public customerData:Customer=null;

  constructor(private rest:REST,private authenticationService : AuthorizationService) {
    super();
    this.componentname=this.constructor.name;
     this.accessLevel=this.authenticationService.isUserLoggedIn()?this.authenticationService.componentAccessLevel(this.constructor.name):null;
     console.log(this.constructor.name +' has '+this.accessLevel);
     if(this.accessLevel==AccessLevel.ENABLED){
       this.getData();
     }
  }

  private getData():any{
    this.rest.get(CustomerComponent.url,this.id).subscribe(data=> this.storeData(data.json()), err => console.log(err) && this.accessLevel==AccessLevel.DISBLED);
  }



private storeData(res:Object):any{
            //TODO
      //this.customerData =<Customer>res;
   this.customerData=<Customer>this.dummy;
}       

这是我休息服务的get方法:

get(resource: string, id: number, params: URLSearchParams = new URLSearchParams()) {
    let headers = this.defaultHeaders;
    headers.set("Authorization", this.authdata);
    return this
        .http
        .get(this.getUrl(resource) + '/' + id, params);
    // .map((r: Response) => r.json());
}

但永远不会执行错误块,storeData(dat.json())函数也是如此。

只有在呼叫成功时才会执行订户块吗?

这里有什么我想念的吗?

由于

1 个答案:

答案 0 :(得分:1)

subscribe(...)支持3次回调

someObservable.subscribe(
  data => this.onSuccessDoSomething(data),
  err => this.onErrorDoSomethingElse(err),
  () => this.afterObservableCompleted() // after the last onSuccess...
)