简体   繁体   English

angular 5+ 相同的路由,相同的组件但不同的参数,不在 angular 订阅上发送 http get 请求

[英]angular 5+ same routing, same component but different param, not send http get request on angular subscribe

This is my app.modules这是我的 app.modules

const appRoutes: Routes = [
  { path: 'topic/:topicTypeAngular', component: StoryTypeComponent, pathMatch : 'full'},
  { path: '**', component: PageNotFoundComponent}
];

This is my nav in html这是我在 html 中的导航

<ul>
    <li> <a routerLink="topic/culture">Culture</a></li>
    <li><a routerLink="topic/tech">Tech</a></li>
</ul>

// Thid is component.ts excerpt and crucial part // 这是 component.ts 的摘录和关键部分

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpRequest, HttpEvent, HttpEventType, HttpParams } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';

   constructor(public http: HttpClient, private route: ActivatedRoute) {
         this.parameter = this.route.snapshot.paramMap.get('topicTypeAngular');
         let parameter = this.parameter;
    }


    ngOnInit() {
         this.route.url.subscribe(parameter => {
         let parameter = this.parameter;
          this.http.get('http://localhost:3200/cookbooks/topic/'+parameter).subscribe(httpResponse => {
              this.data = httpResponse;
              console.log(httpResponse);
            });

        })
     }

The last part does not provide me new httpResponse data.最后一部分没有为我提供新的 httpResponse 数据。 This link similar to my issue but not exact.链接类似于我的问题,但不准确。 However, I tried but failed.但是,我尝试过但失败了。 Thanks in advance提前致谢

What about directly getting the params with a pipe like this :用这样的pipe直接获取参数怎么样:

constructor(public http: HttpClient, private route: ActivatedRoute) {    
  this.route.paramMap.pipe(
    switchMap((params: ParamMap) => {
      this.parameter = params.get('topicTypeAngular');
      return this.http.get(`http://localhost:3200/something/topic/${this.parameter}`);
    })
  ).subscribe(
    result => console.log(result)
  );
}

Try this:尝试这个:

constructor(public http: HttpClient, private route: ActivatedRoute) {}

    ngOnInit() {

    this.route.params.subscribe(param => this.http.get('http://localhost:3200/something/topic/' + param['topicTypeAngular']).subscribe(httpResponse => {
            this.data = httpResponse;
            console.log(httpResponse);
        });)
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM