2016-06-09 118 views
2

如何通過routeparams在routerConfig頁面無需重新加載頁面角2 - 如何通過在routerConfig routeparams無需重新加載

我有的通過routerparams在routerlink一個組件,如下

@Component({ 
    selector: 'apartment', 
    template: ` 
    <div *ngFor="#apartment of apartments" class="demo-updates mdl-card mdl-shadow--2dp mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-cell--12-col-desktop"> 
       <div class="mdl-card__actions mdl-card--border">     
       <a [routerLink]="['AptDetails', {UnitType: apartment.UnitType, aptStatus: 'Available'}]" class="mdl-button mdl-js-button mdl-js-ripple-effect" (click)="getAvailable(apartment)">Available</a>        
       </div> 
    </div> 

在接收組件中的參數被讀出如下,

@Component({ 
    selector: 'aptdetails', 
    template: ` <h1> Apt Details</h1> 
       {{aptDetails | json}} 
    `, 
    directives: [ROUTER_DIRECTIVES] 
}) 

export class AptDetailsComponent implements OnInit { 

    constructor(private apartmentService: ApartmentService, private sharedService: SharedService, params: RouteParams) { 
    this.apartmentService = apartmentService; 
    this.aptStatus = params.get('aptStatus'); 
    this.UnitType = params.get('UnitType');  
    } 

的值被順利通過,但頁面刷新。

如何在不刷新routerLink中的頁面的情況下傳遞參數?

我知道我們可以創建一個共享服務來臨時存儲組件之間的值,我怎樣才能使用routeparams相同?

回答

1

您可以實現CanReuse

class MyComponent implements CanReuse { 
    routerCanReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) { 
    return true; 
    } 
} 

然後導航到只有參數的當前路徑改變不重用現有的組件實例。

+0

我可以在ComponentInstruction通過RouteName這直接樣? 'routerCanReuse(nextInstruction:'AptDetails',prevInstruction:'Apartment')' – user2180794

+0

不,路由器在導航到此組件時正在調用該方法。你不應該自己調用它。您可以使用'routerLink'或'router.navigateXxx(...)'調用,其餘由路由器完成。 –

+0

頁面仍在重新加載,當它要去AptDetails ... ..也許我做錯了什麼。我在路由到AptDetails的ApartmentComponent中加入了'CanReuse' – user2180794

0

使用CanReuse和OnReuse,作爲

export class Component implements OnReuse, CanReuse { 

    routerCanReuse() { 
     if (yourCondition) 
      return true; 
     else 
      return false; 
    } 

    routerOnReuse() { 
     console.log('on reuse'); 
    } 


}