2017-01-24 78 views
2

我在移动到另一个store location时遇到了模板未更新的问题。 (例如)默认为Eastleigh,如果我移动到USA它将更改为USA,但当我去其他地方时,它会卡住USA在angular2中使用routerLink更新模板

我必须刷新页面,以便模板将更新Collection Store - {{}},但不应该如此。

在我的模板html中,我有这个。

<span> Collection Store - {{ currentStore?.Name }}</span> 

地点正在从后台返回 - 使用此服务:

public storesChanged = new BehaviorSubject([]); 

public getStores(): void { 
    this.retrieveResults().subscribe((results) => { 
    this.storesChanged.next(results.Results) 
     console.log('Name >> ', results.Results[0].Name) // this shows me the Name 
    }); 
} 
public retrieveResults(): Observable<any> { 
    return this.http.get('/api/Stores/Summary') 
    .map(res => res.json()) 
} 

组件 -

ngOnInit() { 
    this.routeSub = this.route.params.subscribe(params => { 
     this.storeId = +params['storeId']; 
     this.storeLocation = params['storeLocation']; 
     if (!this.storeId) { 
     this.storeId = DEFAULT_ORIGIN_ID; 
     } 
    }) 

    this.sharedService.storesChanged.subscribe((res) => { 
     this.currentStore = res.find((x) => x.Id === this.storeId); 
     console.log('Change Location >> ', this.currentStore) 
    }) 
    } 

我这是怎么呈现下拉菜单中的网址,

<li *ngFor="let store of sourceSites | slice:1" [class.active-location]="storeId === store.Id"><a id="{{store.Name}}" [routerLink]="['/order-screen/store/' + store.Id + '/' +store.Name]">{{ store.Name}}</a></li> 

有人可以e指出为什么我渲染的模板currentStore?.Name并不总是更新?我不想每次更改页面时刷新页面以选择不同的网址/位置。

固定

ngOnInit() { 
     this.routeSub = this.route.params.subscribe(params => { 
      this.storeId = +params['storeId']; 
      this.storeLocation = params['storeLocation']; 
      if (!this.storeId) { 
      this.storeId = DEFAULT_ORIGIN_ID; 
      } 
      this.sharedService.storesChanged.subscribe((res) => { 
      this.currentStore = res.find((x) => x.Id === this.storeId); 
      console.log('Change Location >> ', this.currentStore) 
      }) 
     }); 
     } 

回答

0

如果这些URL被用于同样的部件。你可以订阅url params变更。 例如

import { ActivatedRoute } from '@angular/router'; 

export class DemoPage { 
    constructor(private _route: ActivatedRoute) { } 
    ngOnInit() { 
      this._route.params.forEach(params => { 
        let storeId= params["storeId"]; 
        this.getStoreInfo(storeId); 
      }) 
    } 
} 
+0

我已经订阅了它,不好意思忘了在上面提到它。我在我的问题中添加了代码。 – MrNew

+0

我想我现在已经修好了,我的'storeChanged'服务在'params.subscribe'之外,它应该在里面。 – MrNew