如何使用Angular 2和TypeScript在promise中设置变量

How to set variable in a promise using Angular 2 and TypeScript

本文关键字:promise 设置 变量 TypeScript 何使用 Angular      更新时间:2023-09-26

我对如何在Angular 2中使用带有TypeScript的promise有点困惑。例如,我创建了一个获取一些JSON的服务,并希望将结果设置为数组。

例如,在Angular 1中,我会执行以下操作:

workService.getAllWork().then(function(result){
  vm.projects = result.projects;
});

在Angular 2中,我有以下服务:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class WorkService {
constructor(private _http: Http) { }
  getAllProjects() {
    return this._http.get('/fixture/work.json')
        .map((response: Response) => response.json().projects)
        .do(projects => console.log('projects: ', projects))
        .toPromise()
        .catch(this.handleError);
  }
  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}

在我的组件中,我有:

import {Component} from '@angular/core';
import {HTTP_PROVIDERS} from '@angular/http';
import {Showcase} from '../showcase/showcase.component';
import {WorkService} from '../services/work.service';
@Component({
  selector: 'App',
  template: require('./landing.html'),
  directives: [Showcase],
  providers: [HTTP_PROVIDERS, WorkService]
})
export class Landing {
  public projects: Array<any>;
  constructor(private _workService: WorkService) {}
  ngOnInit() {
    // How would I set the projects array to the WorkService results
  }
}

如有任何帮助,我们将不胜感激

对于Promise,您可以使用.then(...)来链接调用。

  ngOnInit() {
    this.workService.getAllProjects().then(value => this.projects = value);
  }

你应该知道

  ngOnInit() {
    this.workService.getAllProjects().then(value => this.workService = value);
    // <=== code here is executed before `this.workService.value` is executed
  }

如果你想在承诺解决后执行代码,请使用

  ngOnInit() {
    this.workService.getAllProjects().then(value => {
      this.workService = value;
      // more code here
    });
  }