2016-10-05 129 views
0

我想保存並訪問Angular2對象,但我得到的值未定義。我得到一個對象,但不能訪問,如數組。我怎麼能做到陣列?訪問Angular2對象?

Node.js的api.js

api.get('/getData', function(req, res){ 
    res.send({name:'test'}) 
}); 

的DataService PassProfileDataService.ts

import {Component, Injectable} from '@angular/core' 
import { Http} from "@angular/http"; 


@Injectable() 
export class PassProfileDataService { 

constructor(private http: Http) {} 

getItems(){ 
    return this.http.get('/api/getData').map((res:any) => res); 
} 
} 

組件消耗的服務

import {Component, Input, OnInit} from '@angular/core'; 
import {PassProfileDataService} from '../common/PassProfileDataService'; 


@Component({ 
styleUrls:['/assets/css/bootstrap.css', '/assets/css/profile.css'], 
    selector: "profile", 
    templateUrl: `client/components/profile/profile.component.html` 

}) 

export class ProfileComponent implements OnInit { 

items:any; 

constructor(private _sharedService: PassProfileDataService){} 

ngOnInit(){ 
    this.items = this._sharedService.getItems(); 
    console.log(this.items + ' test'); 
} 

}

視圖組件profile.component.html

<div *ngFor="let i of items"> 
{{i.name}} 
</div> 

我得到以下異常:

core.umd.js:3462 EXCEPTION:無法找到一個不同的支持對象「 [對象]類型的[對象對象]。 NgFor僅支持與陣列等Iterables綁定。

回答

0

TypeScript允許您在定義函數時使用箭頭符號訪問外部函數作用域,方法是將參數括在括號中。

要保存數據的價值簡單地使用:

this.items.subscribe((value) => this.data = value); 

並保存數據,然後儘快到達輸出,你可以使用:

this.items.subscribe((value) => { 
    this.data = value; 
    console.log(this.data); 
}); 
2

this.items.subscribe(...)是異步這意味着它現在不會運行該代碼。 this.items是一個Observable,簡而言之,當最終發生某些事情時,可以通知您並在事件發生時「觀察」事件或一系列事件。在這種情況下,它看起來很像對getUserWishList()的響應承諾。我寫了很多看起來就像這樣的代碼。

如果一切按計劃進行,最終觀察到的訂閱將會觸發,並且this.data將等於value,但我可以保證當您嘗試打印出來時不會在下一行發生。

this.items.subscribe(value => console.log(value));的作品,因爲當事件最終發生火災,你有價值,並可以打印它。

this.items.subscribe(value => this.data = value);也有效。最終。它不會像你期望的那樣快。

你可以修改代碼一點是既:

this.items.subscribe(value => { 
    this.data = value; 
    console.log(this.data); 
}); 

你會在控制檯中看到的價值,如果有的話,勢必this.data也應該反映在視圖中的數據。這可能有點棘手,但如果您在視圖中綁定data.name,如果this.data在Observable回來之前沒有任何東西,則會出現錯誤。

+0

我正在以下錯誤客戶端/組件/配置文件/ profile.component.ts(27,6):錯誤TS2322:類型「任何[]」是不能分配給輸入「可觀察」。 [1] client/components/profile/profile.component.ts(27,6):錯誤TS2322:類型'any []'不可分配給類型'Observable '。 [1]類型'any []'中缺少屬性'_isScalar'。另外我怎樣才能訪問名稱屬性? – Tony

+0

@Tony,這是一個更復雜的打字問題,可能值得一個新的問題。你必須展示更多的代碼才能看到getUserWishList實際返回的是什麼(Observable,但是泛型是什麼?即Observable )以及真正的值是什麼。 –

+0

@Tony,你的'console.log'圖片在你的問題中看起來像'value'只是一個對象而不是數組。由此我認爲價值是一個「任何」,「this.data」不應該是任何形式的可觀察的,this.data應該只是一個「任何」。或者更好的是,一個正確定義的界面。 –

1

這是因爲框架的異步行爲。代碼不會等待您的服務返回。它繼續下一個陳述,在那個時間點,「數據」是未定義的。改變你的代碼如下:

this.items.subscribe(value => this.data = value); 
console.log(this.data); 

到:

this.items.subscribe(value => { 
this.data = value; 
console.log(this.data); 
}); 

你看到區別?我將console.log移至success服務區塊。這是使代碼以同步方式運行的一種快速方法。當你需要的時候,還有其他的方法可以在你的代碼中引入同步行爲,例如Observable.forkJoin。希望你明白了。