获取正确的ID而不共享URL

我有一个Angular 4应用程序,我试图从MySQL数据库中取一行(使用ID)。 我用ExpressJS使用NodeJS。 但是,我正在努力寻找一种方法来从URL获取ID而不共享确切的URLpath,因为这将导致网站只呈现JSON对象,而不是组件。

server.js

app.get('api/books/:id', (req, res) => { console.log(req.params.id); });

如果URL是localhost:3000/books/3 ,控制台将会logging:id
localhost:3000/api/books/3会将正确的IDlogging到控制台。 问题是在我的Angular路由中使用后者作为我的URL会导致共享path,这是行不通的。

以下是我如何使用Angular的HttpModule向服务器发送GET请求的示例:

 this.http.get('api/books/:id') .map(res => res.json()) .subscribe(data => { this.bookDetail = data; }); 

这里是我使用Angular的RouterModule进行路由的path:

 { path: 'books/:id', component: BookDetailComponent } 

我将如何去解决这个问题?

您需要创build一个函数,在该组件的init中,angular度应用程序会触发HTTP请求到服务器。 例如,我有一个博客应用程序。

  { path: 'blogs/:id', component: BlogComponent }, ngOnInit() { this.route.params.subscribe(params => this.blog = params.id); this.getBlog(this.blog);} getBlog(blog) { this.blogService.getBlog(blog).subscribe( data => { this.foundBlog = data; if (data.comments) { this.comments = data.comments; } getBlog(blog): Observable<any> { return this.http.get(`http://localhost:3000/api/blogs/${blog}`).map(res => res.json()); } 

第一个是我的路线,第二个是我的博客组件的初始化函数

第三是博客组件上的获取博客function

最后是我的blogservice上的get博客function,发送HTTP请求

希望这有助于。