2016-08-12 59 views
2

我試圖從我的組件中分離http請求並將其放入服務中,我如何將從請求獲得的響應傳遞給我的組件中的動作?angular2服務傳遞組件的響應

和角1一樣,您可以在控制器中執行類似以下代碼的操作,並在服務中執行http請求。

var getGenreList = function() { 
      coreGenreService.getGenreList(vm.id) 
       .then(function(response) { 
        console.log(vm.name); 
       }); 
     } 

我試過某種應用相同的邏輯,但我不知道如何將響應傳遞給我的控制器。

服務:

getUser(){ 
     this.http.get('http://../api/User?email='+this.customerEmail) 
      .map(response => response.text()) 
      .subscribe(data => { 
       if (data) { 
        var userObj = JSON.parse(data); 
        this.UserEmail = userObj.EmailAddress; 
       } 
     }); 
    } 

我可以看到,這是獲得JSON OBJ文件,但是當我做了搜索,我不看對象中的任何值,我猜,因爲它不是在傳遞在searchUser()

searchUser() { 
    this.isLoading = true; 
    if(!this._searchService.getUser()){ 
     setTimeout(() => { 
      this.isLoading = false; 
     }, 500) 
    } 
} 

HTML輸入結構:

<input type="text" name="UserEmail" [(ngModel)]="customerEmail" placeholder="Search customer email"> <br> 
<button (click)="UserCustomer()" class="omni-btn search-btn float-shadow">Search</button> 

回答

2

您需要refacto [R您服務是這樣的:

getUser(customerEmail: string): Observable<string>{ 
    return this.http.get(`http://../api/User?email=${customerEmail}`) 
     .map(response => response.json()); 
} 

在你的組件,你可以這樣調用服務:

searchUser() { 
    this.isLoading = true; 
    this._searchService.getUser(this.customerEmail) 
    .subscribe(user => { 
     this.isLoading = false; 

     // To use for data binding in the component 
     this.user = user; 

     console.log('user = ', user); 
    }); 
} 
+0

感謝您的答覆,該.subscribe是說對類型「無效」 – nCore

+0

不存在@nCore顯式定義返回類型'getUser():Observable {...}' –

+0

@AndriyTolstoy我在哪裏注入?它說IObservable找不到名字。 – nCore