简体   繁体   中英

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

Im a little confused on how to use promises in Angular 2 with TypeScript. For example I created a service that fetches some JSON and I would like to set the result to an array.

So for example in Angular 1, I would do the following:

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

In Angular 2 I have the following service:

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');
  }
}

And in my component I have:

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

Any help would be greatly appreciated.

For a Promise you use .then(...) to chain a call.

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

You should be aware that

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

If you want to execute code after the promise resolved, use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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