【问题标题】:How to set variable in a promise using Angular 2 and TypeScript如何使用 Angular 2 和 TypeScript 在 Promise 中设置变量
【发布时间】:2016-07-25 10:03:01
【问题描述】:

我对如何在 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
  }
}

我们将不胜感激。

【问题讨论】:

    标签: javascript angularjs typescript angular angular2-services


    【解决方案1】:

    对于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
      }
    

    如果要在 promise 解决后执行代码,请使用

      ngOnInit() {
        this.workService.getAllProjects().then(value => {
          this.workService = value;
          // more code here
        });
      }
    
    猜你喜欢
    • 2016-07-31
    • 2018-01-04
    • 2017-04-05
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多