Angular 2承诺传球

时间:2018-02-20 01:25:46

标签: angular angular-promise es6-promise

我对为什么我无法访问此承诺中的值感到有些困惑。

我有一个带有返回promise的方法的服务,如下所示:

import { MainContent } from './../../shared/mainContent.model';
import { LargeIconCard } from './../../shared/largeIconCard.model';
import { LocoGpsData } from './../../shared/locoGpsData.model';
import { Injectable } from '@angular/core';

@Injectable()
export class MainContentService {

  constructor() { }
  simplePromiseExample(): Promise<MainContent> {
    return new Promise((resolve, reject) => {
      const mainContent = new MainContent();
      mainContent.test = 'test';
      resolve(mainContent);
    });
  }

}

MainContent对象如下所示:

import { LargeIconCard } from './largeIconCard.model';
export class MainContent {
    public largeIconCardList: LargeIconCard[] = new Array();
    public test: string;
    constructor() {}
}

在我的应用程序组件中,我调用服务,返回承诺,并将其设置为&#39; mainContentTest&#39;

import { MainContent } from './shared/mainContent.model';
import { MainContentService } from './services/main-content/main-content.service';
import { LocoGpsData } from './shared/locoGpsData.model';
import { HeaderUserInput } from './shared/headerUserInput.model';
import { Component } from '@angular/core';
import { LocoGpsService } from './services/loco-gps/loco-gps.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  mainContentTest: Promise<MainContent>;

  constructor(
    private locoGpsService: LocoGpsService,
    private mainContentService: MainContentService) {}

  onSearchDataset(userInput: HeaderUserInput) {
      this.mainContentTest = this.mainContentService.simplePromiseExample();
  }
}

在我的app.component.html中如果我执行以下操作,我会看到数据:

{{ mainContentTest | async | json }}

"{ "largeIconCardList": [], "test": "test" }"

我的问题是如何获取此test值?如果我尝试像

那样的话
{{ mainContentTest.test }}

我明白了:

  

无法读取属性&#39; test&#39;未完成的。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

{{ (mainContentTest | async)?.test }}