如何用Promise解决工厂中的依赖?

时间:2017-04-28 10:48:56

标签: angular typescript dependency-injection

我需要通过工厂方法提供服务,该方法根据承诺正确解析服务。我创建了一个简单的组件并编写类。

import {Component, Inject, OnInit} from '@angular/core';
import {basketPriceProvider, IBasketPriceService, IBasketPriceToken} from "./basket-price.interface";

    @Component({
        selector: 'test-inject-component',
        template: `
            <div>
                <p>Price is: {{price}}</p>
            </div>`,
        providers: [
            basketPriceProvider
        ]
    })
    export class TestInjectComponent implements OnInit {
        public title: number;

        constructor(@Inject(IBasketPriceToken) private basketPriceService: IBasketPriceService) {
            console.log(basketPriceService, 'basketPriceService');
        }

        ngOnInit() {
            console.log('init test-inject-component');
            console.log('try to get prices: ', this.basketPriceService.getPrices());
            this.title = this.basketPriceService.getPrices();
        }

    }

工厂/供应商定义

import {Injectable, InjectionToken} from "@angular/core";
import {IUserSession, IUserSessionToken} from "@bf/core";
import {User} from "../../modules/core/shared/models/user.interface";

export let IBasketPriceToken = new InjectionToken('IBasketPriceService');

export interface IBasketPriceService {
    getPrices(): number;
}

@Injectable()
export class CustomerBasketPriceService implements IBasketPriceService {
    getPrices(): number {
        return 0;
    }
}


@Injectable()
export class AnonymousBasketService implements IBasketPriceService {
    getPrices(): number {
        return 1;
    }
}

export let basketPriceFactory = function basketPriceFactory(userService: IUserSession): Promise<IBasketPriceService> {
    return userService.getActiveUser().toPromise().then((user: User) => {
        if (user) {
            return new CustomerBasketPriceService();
        } else {
            return new AnonymousBasketService();
        }
    });
};
export let basketPriceProvider =
    {
        provide: IBasketPriceToken,
        useFactory: basketPriceFactory,
        deps: [IUserSessionToken]
    };

有没有人知道如何在useFactory中使用Promise?

1 个答案:

答案 0 :(得分:1)

由于basketPriceService会返回一个承诺,因此它没有getPrices方法。

可以是

    ngOnInit() {
        this.basketPriceService.then(basketService => {
            this.title = basketService.getPrices();
        });
    }

    async ngOnInit() {
        this.title = (await this.basketPriceService).getPrices();
    }

虽然这是路线解析器的完美案例。