如何从 URL 中获取参数 Angular
How to get parameters from URL in Angular
我在功能模块的 Angular 7 应用程序中包含了路由。属于该特性的组件需要获取路由参数。我该怎么做?
我已经尝试使用文档中显示的方法,如下面的代码所示。我已经评论了哪些有效,哪些无效。我想使用无法使用的第二种方法,因为它将结果映射到我将在模板中使用的 products$
可观察对象。可能是什么问题?
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Observable } from "rxjs";
import { switchMap } from "rxjs/operators";
import { Product } from "@shared/interfaces/product.interface";
import { ProductsService } from "../products.service";
@Component({
templateUrl: "./product-list.component.html",
styleUrls: ["./product-list.component.css"]
})
export class ProductListComponent implements OnInit {
products$: Observable<Product[]>;
constructor(
private route: ActivatedRoute,
private service: ProductsService
) {}
ngOnInit() {
this.route.paramMap.subscribe((params: ParamMap) => {
console.log(params.get("category")); // this works
});
this.products$ = this.route.paramMap.pipe(
switchMap(params => {
console.log(params.get("category")); // this doesn't work
return this.service.getProducts(params.get("category"));
})
);
}
}
我希望第二种方法能记录结果,但根本没有。
rxjs observables 是惰性的,所以如果没有完成订阅,你的源甚至不会尝试获取数据。
在 ngOnInit 的末尾添加 this.products$.subscribe()
,您将看到 console.log 结果。
我接受了 Andrei 的回答,但我也了解到添加 |模板文件中的 async 解决了这个问题,因为正如 Andrei 所指出的,还没有发生任何订阅
Andrei 是真的 rxjs observables 是惰性问题将通过添加 this.products$.subscribe()
来解决,但与 angular Router 不同的是,其他服务订阅在您取消订阅之前不会停止。所以记得取消订阅 ngOnDestroy()
我在功能模块的 Angular 7 应用程序中包含了路由。属于该特性的组件需要获取路由参数。我该怎么做?
我已经尝试使用文档中显示的方法,如下面的代码所示。我已经评论了哪些有效,哪些无效。我想使用无法使用的第二种方法,因为它将结果映射到我将在模板中使用的 products$
可观察对象。可能是什么问题?
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Observable } from "rxjs";
import { switchMap } from "rxjs/operators";
import { Product } from "@shared/interfaces/product.interface";
import { ProductsService } from "../products.service";
@Component({
templateUrl: "./product-list.component.html",
styleUrls: ["./product-list.component.css"]
})
export class ProductListComponent implements OnInit {
products$: Observable<Product[]>;
constructor(
private route: ActivatedRoute,
private service: ProductsService
) {}
ngOnInit() {
this.route.paramMap.subscribe((params: ParamMap) => {
console.log(params.get("category")); // this works
});
this.products$ = this.route.paramMap.pipe(
switchMap(params => {
console.log(params.get("category")); // this doesn't work
return this.service.getProducts(params.get("category"));
})
);
}
}
我希望第二种方法能记录结果,但根本没有。
rxjs observables 是惰性的,所以如果没有完成订阅,你的源甚至不会尝试获取数据。
在 ngOnInit 的末尾添加 this.products$.subscribe()
,您将看到 console.log 结果。
我接受了 Andrei 的回答,但我也了解到添加 |模板文件中的 async 解决了这个问题,因为正如 Andrei 所指出的,还没有发生任何订阅
Andrei 是真的 rxjs observables 是惰性问题将通过添加 this.products$.subscribe()
来解决,但与 angular Router 不同的是,其他服务订阅在您取消订阅之前不会停止。所以记得取消订阅 ngOnDestroy()