Promise.resolve 的示例

服务/ my.service.ts

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

@Injectable()
export class MyService {
    data: any = [1, 2, 3];

    getData() {
        return Promise.resolve(this.data);
    }
}

getData() 现在表现得像一个创建 Promise 的 REST 调用,它会立即得到解决。结果可以在 .then() 内手持,也可以检测到错误。这是异步方法的良好实践和约定。

组件/ my.component.ts

import { Component, OnInit } from '@angular/core';
import { MyService } from '../services/my.service';

@Component({...})
export class MyComponent implements OnInit {
    data: any[];
    // Creates private variable myService to use, of type MyService
    constructor(private myService: MyService) { }

    ngOnInit() {
        // Uses an "arrow" function to set data
        this.myService.getData().then(data => this.data = data);
    }
}