繁体   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.
}

我是Angular2 JS的新手。 如上面的代码,我只想将json响应数据映射到angular2打字稿对象。 我怎样才能做到这一点。 它正在获得“响应”价值。 但是不能映射到人对象。 我想从外面使用响应数据

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

在您PeopleServiceget使用.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.

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