2016-08-24 51 views
0

所以,我有以下服務/組件:入門推遲從訂閱變量Angular2服務

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)); 
    } 
} 

租賃-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方法什麼都不產生,儘管第一次被稱爲subscribe實際上正在工作。

電話訂購:

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

租金構成是通過路由器出口儀表板組件上兩個孩子,所以它們不是直接分量。

我想過要等待訂閱完成的變量,我嘗試使用承諾,但他們永遠不會返回訂閱的價值,這是我想出來的最好的,但它不起作用。這是我第一次使用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" 
+0

附加註釋:我應該使用某種商店,因爲服務正在被許多組件重用? – zbrukas

+0

對我來說,你實際上試圖完成的事情還不太清楚。什麼是「經理」?你多久需要取回它?只有在啓動時或每次出租搜索時纔有一次? –

+0

@GünterZöchbauer我只是在開始時加載它。經理有客戶,出租等,我想分開他們自己的服務,因爲他們有自己的儀表板。 – zbrukas

回答

0

我想改變觀察到在RentalService

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

應該做你想要什麼