【问题标题】:Navigating to a new route doesn't load component data in Angular导航到新路线不会在 Angular 中加载组件数据
【发布时间】:2020-08-24 01:12:26
【问题描述】:

我正在渲染一个 Angular 组件,以便根据实体的 id 显示数据

<a *ngFor="let detail of details" [routerLink]="['/record-details', detail.id">
  Go to page {{detail.name}}
</a>

record-details.component.ts

public id;
public issueDetails;

constructor(
    private route: ActivatedRoute,
    private recordDetailsService: RecordDetailsService,
) {
    route.params.subscribe(params => this.id = params.id);

}

async ngOnInit() {
    await this.getDetails(this.id);
}

async getDetails(id) {
    try {
      this.issueDetails = await this.recordDetailsService.getDetails(id);
    } catch (e) {
      console.error(e);
    }
}

但每当我点击 html 链接转到新页面时,它只会更改路由参数。我也想根据新的id 加载数据

我做错了什么?

app-routing.module.ts

{
    path: 'record-details',
    canActivate: [AuthGuard],
    loadChildren: () => import('./record-details/record-details.module').then(m => m.RecordDetailsModule)
},

record-details-routing.module.ts

const routes: Routes = [
  {
    path: ':id',
    component: RecordDetailsComponent
  }
];

【问题讨论】:

  • 你能在你定义路线的地方显示代码吗?
  • @Alexander 检查我更新的问题

标签: angular routes components router routerlink


【解决方案1】:

查看代码时,我突然想到为什么要使用 async 和 await。有了角度,我会倾向于使用 observables。

public id;
public issueDetails;

constructor(
    private route: ActivatedRoute,
    private recordDetailsService: RecordDetailsService,
) { }

ngOnInit() {
    this.id = route.snapshot.paramMap.get('id');
    this.getDetails(this.id);
}

getDetails(id) {
    this.recordDetailsService.getDetails(id).subscribe(issueDetails => {
        this.issueDetails = issueDetails;
    }, error => console.error(error));
}

您还需要将您的 recordDetailsS​​ervice 更改为可观察的

【讨论】:

  • 我切换回 observables 但它仍然没有更新组件数据
【解决方案2】:

我设法让它工作,检查hero-detail component

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    相关资源
    最近更新 更多