2017-02-09 39 views
0

我是新來的離子和角度,以及從多年.NET開發的未來。我想舉幾個例子網上建立登錄原型離子2.離子2返回前檢查可觀察到它

我的WebAPI在後臺工作簡單地返回JSON true或false取決於如果傳遞的憑據正確與否。

我得到了驗證提供這樣看:

public login(credentials) { 
    if (credentials.email === null || credentials.password === null) { 
     return Observable.throw("Please insert credentials"); 
    } else { 

     this.result = this.http.post(this.CONST.APIUrl, JSON.stringify(credentials), new RequestOptions({headers: this.contentHeader})).map(res => res.json()) 

     if (this.result) 
     { 
      this.currentUser = new User('Simon', '[email protected]'); 
     } 

     return this.result; 

    }} 

和登錄頁面看起來像這樣:

public login() { 
    this.showLoading() 
    this.auth.login(this.registerCredentials).subscribe(allowed => { 
     if (allowed) { 
     setTimeout(() => { 
     this.loading.dismiss(); 
     this.nav.setRoot(HomePage) 
     }); 
     } else { 
     this.showError("Access Denied"); 
     } 
    }, 
    error => { 
     this.showError(error); 
    }); 
    } 

在它總是記錄的人在那一刻我明白,這種情況正在發生,因爲這.result總是有價值的。但是,在允許人員登錄之前,如何檢查從API返回的數據?

回答

0

您可以使用Observable.do爲Observable創建副作用

在登錄功能:

public login(credentials) { 
    if (credentials.email === null || credentials.password === null) { 
     return Observable.throw("Please insert credentials"); 
    } else { 

     this.result = this.http.post(this.CONST.APIUrl, 
      JSON.stringify(credentials), new RequestOptions({headers: this.contentHeader})) 
      .map(res => res.json()) 
      .do(userData=>{ 
       //check userData and set current user 
       this.currentUser = new User('Simon', '[email protected]'); 
       return userData;//make sure to return the value to subscribe 
      }); 
    return result; 
    }}