简体   繁体   English

映射http请求将json数据响应到Angular2对象并从外部访问

[英]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.
}

I'm newbie to Angular2 JS. 我是Angular2 JS的新手。 As above code, I just want to map the json response data to angular2 typescript object. 如上面的代码,我只想将json响应数据映射到angular2打字稿对象。 How can I do this. 我怎样才能做到这一点。 It is getting 'response' value. 它正在获得“响应”价值。 But can not map to person object. 但是不能映射到人对象。 I want to use response data from the outside 我想从外面使用响应数据

.subscribe(response => this.person = .json().data as Person); // get response value

在您PeopleServiceget使用.publishLast().refCount()来缓存结果/

If you want to use your response, eg in a method in your component, the easiest way would be to call that method from inside the subscription, after you have got your value to person : 如果您想使用响应,例如在组件中的方法中,最简单的方法是在获得对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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM