2016-11-16 31 views
1

在我的組件我打電話REST服務,並要保存數據,其餘的呼叫不成功(預期行爲),所以我期待這個代碼被執行:Angular2:HTTP觀測流量不明確

ERR =>執行console.log(ERR)& & 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()); 
} 

但是error block永遠不會執行,storeData(dat.json())函數也不會執行。

只有在呼叫成功時,用戶塊才能執行嗎?

有什麼我在這裏失蹤?

感謝

+0

能否請你定義 '並不成功'?它是否返回一個錯誤代碼或者根本不可能連接? – Sebastian

回答

1

subscribe(...)支持3個回調

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

重要的是要注意'onCompleted'不在錯誤情況下被調用,而只在'onNext'情況下被調用。 – Sebastian

+0

您是否暗示代碼因爲缺少參數而無法使用?如果是這樣,那麼我認爲JavaScript會爲第三個參數傳遞null,並且調用仍然可以工作。 – bassxzero

+0

試圖回答「只有在呼叫成功後才執行用戶塊嗎?」這個問題。 –