Object/array passing in the RouteParams via Routin

2020-03-24 07:56发布

问题:

Working on Routing in angular2. actually i know we can send key/value using RouteParams in the routing but i want to send whole object/array in the RouteParams, i don't know is it possible or not. is there any way to do so if not then any alternate who knows ?

my current HTML part is :

<div *ngFor="#books of getBooks_array #i=index">
    <a [routerLink]="['/IssueBook', {name: books.book_name, isbn: books.book_ISBN,author: books.book_author, price: books.book_price, id: books.book_id, language: books.book_language}]"></a>
</div>

my current .ts conatins:

constructor(@Inject(RouteParams) params:RouteParams, @Inject(Http) http:Http){
        this.name= params.get('name');
        this.id= params.get('id');
        this.language= params.get("language");
        this.price= params.get("price");
        this.author= params.get("price");
        this.isbn= params.get("isbn");
}

but i want to send RouteParams like this :

<div *ngFor="#books of getBooks_array #i=index">
<a [routerLink]="['/IssueBook', {data: books}]">Books</a>
</div>

and i am trying to get data like this:

constructor(@Inject(RouteParams) params:RouteParams, @Inject(Http) http:Http){
        this.data= params.get('data');
}

but i am getting error :

回答1:

You can pass Objects to Url's in Angular2, but it's not really supported. The get-Method on routeParams only returns a string-representation, so you would get a string like "[Object]". If you want to access the passed data, you need to use the params-Property:

constructor(@Inject(RouteParams) params:RouteParams, @Inject(Http) http:Http){
    this.data= params.params.data;
}

But beware, this only works properly the first time you call the route. If you call the route anothertime with different data, it can happen that params.params.data returns your old data although you put new data into the route.



标签: angular