2016-08-24 52 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(); 

应该做你想要什么