代码之家  ›  专栏  ›  技术社区  ›  Ahmad Sharif

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

  •  0
  • Ahmad Sharif  · 技术社区  · 7 年前

    这是我的应用程序模块

    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>
    

    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数据。 这 link 类似于我的问题,但不确切。然而,我尝试了,但失败了。提前谢谢

    2 回复  |  直到 7 年前
        1
  •  1
  •   Ahmad Sharif    6 年前

    试试这个:

    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);
            });)
     }
    
        2
  •  2
  •   Johan Rin    7 年前

    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)
      );
    }
    
    推荐文章