Angular 2的问题承诺传递对象

时间:2016-07-19 22:05:17

标签: javascript typescript angular angular-promise

我在使用承诺在Angular 2中返回Degree对象时遇到问题。 degree.service 中的第一个return语句(未注释)与getDegree()的未注释实现结合使用效果很好在 build.component 中。但是,当我尝试使用promise切换到任何一个注释实现时,该对象总是以“undefined”形式返回

degree.service.ts

import { Injectable } from '@angular/core';

import { Degree } from '../components/degree';
import { Category } from '../components/category';
import { Course } from '../components/course';

import { SAMPLE } from '../components/mock-degree';

@Injectable()
export class DegreeService{
  getDegree(){
    return SAMPLE;
    // return Promise.resolve(SAMPLE);
    // return new Promise<Degree>(function (resolve, reject) {
    //  resolve(SAMPLE);
    // })
  }
}

build.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES } from "ng-semantic";

import { Course } from '../course';
import { Category } from '../category';
import { PaneComponent } from './pane/pane.component';
import { Degree } from '../degree';

import { DegreeService } from '../../services/degree.service';


const blank: Category = {
  name: '',
  rank: 1,
  rulestat: 'no',
  categories: [],
  courses: []
}

@Component({
    selector: 'my-build',
    directives: [SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES, PaneComponent],
    templateUrl: `app/components/build/build.component.html`,
    providers: [DegreeService]
})



export class BuildComponent implements OnInit{
  constructor(private degreeService: DegreeService){}

  level: number = 1;
  currDeg: Degree;
  parents = [blank, blank, blank, blank];


  setLast(lst: Category){   //pass category objects, do all UI changing here
    this.level = lst.rank + 1;
    this.parents[lst.rank - 1] = lst;
  }

  getDegree(){
    //this.degreeService.getDegree().then(deg => this.currDeg = deg)
    this.currDeg = this.degreeService.getDegree();
  }

  ngOnInit(){
    this.getDegree();
  }
}

1 个答案:

答案 0 :(得分:0)

我不知道你如何在你的模板中使用currDeg但是使用promises,事情是异步的。因此,相应的对象在开始时将是未定义的,因为它将在稍后设置(当promise被解析时)。而且,即使承诺直接通过Promise.resolve解决。

export class DegreeService{
  getDegree(){
    return Promise.resolve(SAMPLE);
  }
}

@Component({
  selector: 'my-app',
  providers: [DegreeService],
  templateUrl: 'src/app.html'
})
export class App {
  constructor(private degreeService:DegreeService) {
  }

  getDegree(){
    this.degreeService.getDegree().then(deg => {
      this.currDeg = deg;
      console.log('this.currDeg = ' + this.currDeg); // <------
    });
  }

  ngOnInit(){
    this.getDegree();
  }
}

请参阅此plunkr:https://plnkr.co/edit/1fxE0okyMNj2JktURY4w?p=preview