angular2 resolve observable - 如何捕获新数据

时间:2017-07-22 09:54:09

标签: javascript angular angular2-routing

这是我的解析器

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { ContractService, UserContract } from './';

@Injectable()
export class UserContractsResolver implements Resolve<UserContract> {
    constructor(private contractsService: ContractService) {}

    public resolve(): any {
        return this.contractsService.getUserContracts().map(contracts => {
            return contracts;
        }).first();
    }
}

和我的服务

@Injectable()
export class ContractService {
    public userContracts: ReplaySubject<User> = new ReplaySubject(1);

    constructor(private http: AuthHttp) {}

    public getUserContracts() {
        if (!this.user.observers.length) {
            this.http.get('url')
                .map(response => response.json())
                .subscribe(contracts => {
                    this.nextUserContracts(contracts);
                });
        }

        return this.userContracts;
    }
}

和我的组件

export class Test implements OnInit {
    constructor() {
        // option1: get data from router
        this.route.data.subscribe(data => {
            console.log(data['contracts']);
        });
        // option2: get data from service
        this.contractService.getUserContracts().subscribe(contracts => {
            console.log(contracts);
        });
    }

    next() {
        this.contractService.userContracts.next([]);
    }
}

问题是当数据(可观察)更新时(例如调用next()函数)我只能用option2(service)捕获它。也许我理解错了,但我想用option1(解析器)来捕捉它。

有可能吗?

0 个答案:

没有答案