Angular 路由查询参数需要两个事件并定义一个';全球';可变Onit
我的应用程序使用服务和单个组件,如下所示: data.service.ts-此服务“获取”来自两个不同api调用的响应,并将存储的路由查询参数(路由id)传递给其中一个api URL:Angular 路由查询参数需要两个事件并定义一个';全球';可变Onit,angular,Angular,我的应用程序使用服务和单个组件,如下所示: data.service.ts-此服务“获取”来自两个不同api调用的响应,并将存储的路由查询参数(路由id)传递给其中一个api URL: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { retry,
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { course } from './shared/course';
@Injectable({
providedIn: 'root'
})
export class DataService {
url_json = 'api url'
url_course = 'api url'
constructor(private http: HttpClient) { }
getMenus() {
return this.http.get(this.url_course)
}
getContent(id): Observable<course> {
return this.http.get<course>(this.url_json + '/' + id) //this id comes from the route
}
}
nav.component.html-路由将索引id分配为queryParam,get_id(id)将id值传递回nav组件,并将其存储在其中以与rest调用端点一起使用
<div *ngFor="let menu of menus; index as id">
<ul>
<li><a routerLink = "" [queryParams]="{id: id}" (click)="get_id(id)">{{menu['lessonName']}}</a></li>
</ul>
</div>
<div *ngIf="content">
{{content.id}}
</div>
- {{菜单['lessonName']}
{{content.id}
问题:除两个小错误外,所有功能都正常工作,我需要一些关于可能问题的建议或想法:
谢谢您的帮助。您想根据路由参数发出API请求。这只是将API调用链接到可观察路由的一个例子
route.queryParams
是一个主题
,当查询参数更改时,它会发出一个新值。因为它是用行为子对象实现的,这意味着你也会得到一个初始值
任何依赖于查询参数的内容都应该链接到queryParams
,并使用switchMap
进行观察
导出类NavComponent实现OnInit{
//用于保存数据的可伸缩性
菜单;
内容;
构造函数(私有数据:DataService,私有路由:ActivatedRoute){}
恩戈尼尼特(){
this.data.getMenus().subscribe((数据:{})=>this.menus=data);
this.route.queryParams.pipe(
switchMap(params=>this.data.getContent(params.id))
).subscribe((响应:{})=>{
这个。内容=响应;
});
}
}
由于组件现在负责在查询参数更改时调用服务,因此不需要从HTML调用它
-
{{菜单['lessonName']}
{{content.id}
因此,现在的事件流是:
- 1a。加载菜单
- 1b。基于初始查询参数加载内容
-
- 用户点击菜单链接
-
- 查询参数已更新
-
- 您的
switchMap
使用最新的查询参数进行新的服务调用
1a和1b不是同步的,但它们似乎彼此独立,所以现在这不是问题
通常情况下,你会被要求退订的主题,但路由器是一个特殊的情况下,清理后,它本身,所以你不必手动退订
<div *ngFor="let menu of menus; index as id">
<ul>
<li><a routerLink = "" [queryParams]="{id: id}" (click)="get_id(id)">{{menu['lessonName']}}</a></li>
</ul>
</div>
<div *ngIf="content">
{{content.id}}
</div>