Angular2 use object name in route but send id in h

2019-09-17 20:05发布

问题:

Hello

I have an angular2 application that shows posts from an api.

when user navigate to a route i use the category name in browser like this :

www.example.com/sport .

but my server only accepts id and not the name.

so my question is : how can i send id to server but show name in url when user navigates to the page.

below is my code :

this is my category list component :

these are my links to the categories and im passing the name of category with some text for its prepend.

<section class="categories_div no-padding">

<div class="col-md-12  col-xs-12 text-center">

    <ul class="list-group ul_categories text-center">
        <li *ngFor="let cat of categories" class="text-center"><a class="categories_list_link"  routerLink="/{{prependUrl+cat.name}}" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" >{{cat.name}}</a> </li>
    </ul>
</div>

</section>

this is my category item component

i am getting the name here and remove that prepend then i am using service to get the posts for this category.

ngOnInit() {
    let name = this.route.snapshot.params['category'];
    name = name.replace('posts-', '');
    this.getCategoryNews(name);

}

getCategoryNews(category:string):any {
    this.categoryService.getCategoryNews(category).subscribe(result => {

                this.allNews = result.data
        },
        err => {
            alert('we have error in connection');
        }
    );
}

and here is my categoryService

import {Injectable} from "@angular/core";
import {Headers, Http, Response} from "@angular/http";
import "rxjs/Rx";
import {Observable} from "rxjs/Rx";

@Injectable()
export class CategoryService {

private CategoryUrl = 'http://test.com/v1/category';
private headers = new Headers({'Content-Type': 'text/plain',});


constructor(private http:Http) {
}

getCategories():Observable<any> {
    return this.http.get(this.CategoryUrl)
        .map((response:Response) => response.json());
}

getCategoryNews(id:number):Observable<any> {
    const url = `${this.CategoryUrl}/${id}`;
    return this.http.get(url)
        .map((response:Response) => response.json());
}

somehow i just need to pass category id to my service but showing its name in url.

标签: angular