簡體   English   中英

angular 5+ 相同的路由,相同的組件但不同的參數,不在 angular 訂閱上發送 http get 請求

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

這是我的 app.modules

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

這是我在 html 中的導航

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

// 這是 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);
            });

        })
     }

最后一部分沒有為我提供新的 httpResponse 數據。 鏈接類似於我的問題,但不准確。 但是,我嘗試過但失敗了。 提前致謝

用這樣的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)
  );
}

嘗試這個:

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