【问题标题】:how to route on same component in angular?如何以角度路由相同的组件?
【发布时间】:2018-11-23 20:11:37
【问题描述】:

这里我有多个用户列表。用户ID就像(1,2,3,4,5 ....),单击按钮显示第一个用户详细信息,然后单击第二个用户详细信息按钮显示第二个用户详细信息这是我想要的功能。

但是当我点击第二个用户详细信息按钮时,网址发生了变化,但仍然没有显示第二个用户详细信息,它显示了第一个用户详细信息。那么如何使用用户 ID 在同一页面上路由。

app-routing.module.ts

{ path: 'details/:userid', component : DetailsComponent}

details.component.html

<button mat-raised-button routerLink="details/{{userObj.userid}}">View<button>

details.component.ts

userObj: User[] = [];

constructor(private userService : UserService,private : ActivatedRoute){}

ngOnInit() {  
  const userid= +this.route.snapshot.paramMap.get('userid');    
  this.userService.getUsersDetails({'userid' : userid}).subscribe(
    (data) => {
      if(data.payload != undefined && data.payload != ''){
        this.userObj= data.payload;
      }
    }
  )
}

【问题讨论】:

  • 能否提供您的组件的完整代码
  • @mika 我编辑我的代码
  • 我认为要获得更新的userid,您必须订阅route.params,而不是使用route.snapshot。看看我的回答,看看是否有帮助。

标签: angular


【解决方案1】:

我认为这里真正的问题是您使用的是snapshot.paramMap。如果你使用snapshot.paramMap,在大多数情况下你不会得到更新的状态参数。

要解决这个问题,只需将subscribe 发送到route.params Observable。您将在订阅时获得params,您可以使用它来获得userid。试试看吧:

ngOnInit() {
  this.route.params.subscribe(params => {
    userid = params['userid'];
    this.userService.getUsersDetails({
      'userid': userid
    }).subscribe(data => {
      if (data.payload != undefined && data.payload != '') {
        this.userObj = data.payload;
      }
    });
  });
}

【讨论】:

【解决方案2】:

我认为当您不绑定到 routerLink 时,字符串插值不起作用。

试试这个:

<button mat-raised-button [routerLink]="['details', userObj.userid]">View<button>

【讨论】:

    【解决方案3】:

    您没有分享您的代码源或您已经尝试过的内容,但尝试这取决于您描述的内容

    HTML

    <ng-container *ngFor="let userId in userObj">
      <button mat-raised-button routerLink="[ '/details', userId]">View<button>
    </ng-container>
    

    你必须循环 userObj array 问题是你没有迭代 userObj 的 array 所以当你执行这个 routerLink="details/{{userObj.userid}}" 它需要所有按钮都具有相同的用户 ID。

    【讨论】:

      【解决方案4】:

      据我了解,this.userService.getUsersDetails() 不会将任何用户 ID 作为输入,因此您始终会为任何用户 ID 链接获取相同的数据。

      应该是这样的.userService.getUsersDetails(userId)

      userId: string;
          constructor(private route: ActivatedRoute) {
          }
      
          ngOnInit() {
              this.route.paramMap
                  .pipe(switchMap((params: ParamMap) => {
                      const userId = params.get("userId");
      
                      this.userService.getUsersDetails(userId).subscribe((data) => {
                          if (data.payload != undefined && data.payload != '') {
                              this.userObj = data.payload;
                          }
                      }, (errorResponse) => {
                      });
                      return of(params);
                  }))
                  .subscribe();
          }
      

      【讨论】:

      • 我编辑我的代码,使用用户 ID 我得到了特定的用户详细信息,但是当 id 更改用户 ID 时 userService 没有被调用
      • 我需要稍微了解一下。您在详细信息中并且想要导航到其他页面?如果不是这样,那么您应该使用另一种方法来处理它,而不是在 ngInit 上,因为它将仅在页面加载而不是在 url 更改时进行初始化(因为这里没有发生路由)
      • 我想在同一页面上路由,但用户 ID 不同
      【解决方案5】:

      请根据您的组件和服务尝试以下代码和修改更改。

      第 1 步: 路由器链接示例

      <a [routerLink]="['/details/1']">User Detial</a>
      

      第 2 步:使用示例数据创建服务。

      import { Injectable } from '@angular/core';
      import { Observable, of } from 'rxjs';
      
      @Injectable({
        providedIn: 'root'
      })
      export class ContactsService {
      
        contacts: Contact[] = [];
        constructor() {
          this.contacts.push({ id: 1, name: 'A' });
          this.contacts.push({ id: 2, name: 'B' });
          this.contacts.push({ id: 3, name: 'C' });
          this.contacts.push({ id: 4, name: 'D' });
      
        }
        getContact(id: number): Observable<Contact> {
          return of(this.contacts.find(x => x.id == id));
        }
      }
      
      export class Contact {
        name: string;
        id: number;
      }
      

      第 3 步:创建用于显示用户 ID 和名称的 HTML。

      <p>{{contact.id}}: {{contact.name}}</p>
      <input type="button" (click)="onNext()" value="Next">
      

      第 4 步: 用户详细信息组件

      import { Component, OnInit } from '@angular/core';
      import { Router, ActivatedRoute } from '@angular/router';
      import { map } from 'rxjs/operators'
      import { ContactsService, Contact } from '../contacts.service';
      
      @Component({
        selector: 'app-user-detail',
        templateUrl: './user-detail.component.html',
        styleUrls: ['./user-detail.component.css']
      })
      export class UserDetailComponent implements OnInit {
        contact: Contact;
        userId: number;
        constructor(private route: ActivatedRoute, private router: Router, private contactsService: ContactsService) { }
      
        ngOnInit() {
          this.route.params
            .pipe(map(params => params['userid']))
            .subscribe((id) => {
              this.userId = id;
              this.contactsService
                .getContact(id)
                .subscribe(contact => this.contact = contact);
            });
        }
      
        onNext() {
          let id = parseInt(this.userId.toString()) + 1;
          this.router.navigate(['/details/' + id]);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 2021-04-22
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2019-02-14
        相关资源
        最近更新 更多