从Angular2服务中的订阅获取延迟变量

时间:2016-08-24 23:18:52

标签: angular rxjs angular2-routing observable angular2-services

所以,我有以下服务/组件:

dasboard.service.ts(摘录)

@Injectable()
export class DashboardService extends RestHelpers {
    private _Manager$: Subject<Manager> = new Subject();

    constructor(private http: Http) {
        super(http);

        this.get<Manager>(url).subscribe(result => {
            this._Manager$.next(result);
        }, error => this.errorMsg = error);
    }

    get manager$(): Observable<Manager> {
        return this.Manager$.asObservable();
    }
}

rental.service.ts(摘录)

@Injectable()
export class RentalService extends RestHelpers {
    constructor(private http: Http, private _dashboardService: DashboardService) {
        super(http);

        this._dashboardService.manager$.subscribe(r => {
            this._rentals = r.Rentals;
            this._rentals$.next(this._rentals);
        });
    }

    get rentals$(): Observable<{}> {
        return this._rentals$.asObservable();
    }

    findRental(id: string): Observable<Rental> {
        return this.rentals$.map((r: Rental) => r.find(rental => r.RentalId === id));
    }
}

rental-detail.component.ts(摘录)

export class RentalDetailsComponent implements OnInit {

    private rental: Rental;
    public title = "Rental";

    constructor(private _rentalService: RentalService, private route: ActivatedRoute, private router: Router) {
        this.rental = <Rental>{};
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            let id = params['id'];

            if (id !== undefined) {
                this._rentalService.findRental(id).subscribe((rental) => {
                    this.rental = rental;
                    this.title = rental.RentalName; 
                });
            }
        });
    }
}

构建组件时,已经在另一个组件上调用了一次该服务,当我想将其路由到详细信息时,我永远无法获得租用。在组件调用上,服务被启动(构造函数运行),但似乎subscribe方法什么也没产生,虽然第一次调用它时订阅实际上正在工作。

通话顺序:

Dasboard Component --- Dashboard Service
|
+ Rental Dashboard Component --- Rental Service --- (depends on) Dashboard Service
  |
  + Rental Details Component --- Rental Service --- (depends on) Dashboard Service

租赁组件是通过路由器插座在仪表板组件上的子项,因此它们不是直接组件。

我已经考虑过观看一个变量来等待订阅完成,我尝试使用promises但是它们永远不会返回订阅的价值,这是我提出的最好但是它不起作用。这是我第一次使用rxjs和angular2,我无法解开这个结。非常感谢帮助。

package.json(摘录)

"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/http": "2.0.0-rc.5",
"@angular/router": "3.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "2.0.0-rc.5",
"angular2-in-memory-web-api": "0.0.15",
"core-js": "^2.4.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"systemjs": "0.19.27",
"zone.js": "^0.6.12"

1 个答案:

答案 0 :(得分:0)

我认为将RentalService中的observable更改为

private _rentals$: Subject<Rental> = new BehaviorSubject();

应该做你想做的事情