[英]Modifying object at service layer in angular2: Subscription is not assignable to the type observable
我是Angular2框架的新手,因此如果這是一個基本問題,請原諒。
我正在通過HTTP包裝返回的服務層處理對象。 該對象應該傳遞給組件,但是首先應該對數據進行操作,並且僅提取和轉發必要的數據。
當我嘗試執行此操作時,我收到錯誤消息“無法將訂閱分配給可觀察的類型”。 這是代碼
return this.httpGet<UserInfo[]>(url, {headers}).switchMap(data => data)
.subscribe(
data => {
console.log("new values are going to be" + JSON.stringify( data[0].address.addressLine1));
this.userInfo[0].name = "test name";
this.UserInfo[0].address.city = data[0].address.city;
this.UserInfo[0].address.state = data[0].address.state;
},
);
現在,我認為有意義的是,首先在訂閱中將其轉換回流時將其轉換為數據,然后顯式返回該對象,但這也無法提供所需的輸出,即使類型是可觀察的也是如此。 來自Java oop背景,在這里我看不到問題是什么,這是一個非常困惑的問題。 任何見解均表示贊賞。
編輯:為了完成,在這里進行服務呼叫-
this.inputFormControl.valueChanges
.debounceTime(4000)
.switchMap(query => this.userService.search(query))
.subscribe(
data => {
this.data = data;
},
);
在您當前的代碼中,您已經訂閱了觀察者。 這樣就返回了Subscription而不是Observable。 然后在您的調用函數中,嘗試將其分配給可觀察對象。 嘗試以下模式
someFunction() {
return this.httpGet<UserInfo[]>(url, {headers}).switchMap(data => data)
}
callingFuction(){
someFunction().subscribe(
data => {
console.log("new values are going to be" + JSON.stringify( data[0].address.addressLine1));
this.userInfo[0].name = "test name";
this.UserInfo[0].address.city = data[0].address.city;
this.UserInfo[0].address.state = data[0].address.state;
},
);
}
如其他答案中所述,您將返回訂閱而不是Observable。 我也看不出為什么在服務中需要使用switchMap
(我假設您在服務中有http請求),因為您正在組件中使用它。 因此,我將在服務中進行map
在那里修改數據並將其返回給您的組件。
再指出一件事,在當前代碼中,您不會從http請求中返回任何內容,因此您需要添加一個return語句。
return this.httpGet<UserInfo[]>(url, {headers})
.map(data => {
this.UserInfo[0].name = "test name";
this.UserInfo[0].address.city = data[0].address.city;
this.UserInfo[0].address.state = data[0].address.state;
return this.UserInfo; // add return!
});
您的組件代碼將保持原樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.