【问题标题】:Map http request respond json data to Angular2 object and access from outside将 http 请求响应 json 数据映射到 Angular 2 对象并从外部访问
【发布时间】:2017-08-02 00:27:24
【问题描述】:
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 typescript 对象。我怎样才能做到这一点。它正在获得“响应”价值。但不能映射到人对象。我想使用来自外部的响应数据

【问题讨论】:

  • 你能在这里分享你的 JSON 响应吗!
  • 从外部访问它外部是什么意思?
  • ngOnInit() 方法范围之外

标签: javascript json http angular typescript


【解决方案1】:

如果您想使用您的响应,例如在您的组件中的方法中,最简单的方法是从订阅内部调用该方法,在您获得 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!
}

【讨论】:

  • 这两个答案对您有帮助吗? :)
【解决方案2】:

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

在你的PeopleService 上你的get 使用.publishLast().refCount() 来缓存结果/

【讨论】:

  • 我想将 json 数据映射到 person 对象并从外部使用它
猜你喜欢
  • 2011-01-10
  • 2017-10-27
  • 2020-02-05
  • 2020-08-08
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
  • 2016-11-07
  • 2018-08-20
相关资源
最近更新 更多