![](/img/trans.png)
[英]Map a JSON API object returned from a Http request in JavaScript/Angular
[英]Map http request respond json data to Angular2 object and access from outside
export class PersonEditDetailsComponent implements OnInit,OnDestroy {
person: Person;
sub: any;
constructor(private peopleService: PeopleService,
private route: ActivatedRoute,
private router: Router) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = Number.parseInt(params['id']);
console.log('getting person with id: ', id);
this.peopleService
.get(id) // send http request
.subscribe(response => this.person = response); // get response value
});
}
//I want to access this.person values here.
}
我是Angular2 JS的新手。 如上面的代碼,我只想將json響應數據映射到angular2打字稿對象。 我怎樣才能做到這一點。 它正在獲得“響應”價值。 但是不能映射到人對象。 我想從外面使用響應數據
.subscribe(response => this.person = .json().data as Person); // get response value
在您PeopleService
您get
使用.publishLast().refCount()
來緩存結果/
如果您想使用響應,例如在組件中的方法中,最簡單的方法是在獲得對person
的價值之后從訂閱內部調用該方法:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = Number.parseInt(params['id']);
console.log('getting person with id: ', id);
this.peopleService
.get(id)
.subscribe(response => {
this.person = response;
this.doSomething(); // call method here!
});
});
}
doSomething() {
console.log(this.person) // here value is available!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.