如何解决将参数传递给 ngOnInit 中的方法甚至不调用服务,不记录任何内容
在我创建的上一个组件页面上,一旦您单击一个按钮,它就会使用导航将您带到某个其他组件。考虑到我必须编写两个参数,一个用于当前路径,第二个用于下一个,当我尝试订阅它时,它给了我一个包含 2 个元素的对象。
onSelect(subCategory) {
this.router.navigateByUrl(
`web-shop/categories/${this.type}/${subCategory.nextType}`
);}
在 ngOnInit 中,我捕获了该对象,将其更改为数组并将其值赋予另一个变量。然后我取了数组的第二个元素。当我在代码中调用 this.products
中的一个方法,并过滤它,然后记录它时,我在 console.log 中什么也没得到,即使我传递了我需要的实际值,我检查了看看值是否是我需要的。但出于某种原因,对于 console.log
的 this.products
没有任何结果,甚至没有数组或值。
import { Component,OnInit } from "@angular/core";
import { Router,ActivatedRoute } from "@angular/router";
import { Subscription } from "rxjs";
import { SingleProductModel } from "./../../Models/webshopModels/single-product.model";
import { SingleProductService } from "./../../Services/webshopServices/single-product.service";
@Component({
selector: "app-products",templateUrl: "./products.component.html",styleUrls: ["./products.component.scss"],})
export class ProductsComponent implements OnInit {
type: string;
products: SingleProductModel[];
s: string;
type1: Array<any>;
constructor(
private productsService: SingleProductService,private route: ActivatedRoute,private router: Router
) {}
ngOnInit() {
this.route.params.subscribe((data) => {
this.type1 = Object.values(data);
console.log(this.type1);
this.type = this.type1[1];
console.log(this.type);
this.products = this.productsService
.getCategoryProducts()
.filter((a) => (a.type = this.type));
console.log(this.products);
});
}
}
我什至尝试在服务本身内部过滤它。不在我发送的示例中。
getCategoryProducts() {
return this.product.slice();
}
解决方法
在过滤器语句中,您实际上使用了 =
的赋值而不是比较。
使用 =
或 ==
代替 ===
。
this.productsService
.getCategoryProducts()
.filter((a) => (a.type === this.type))
.subscribe(products => this.products = products);
所以我解决了这个问题。问题是,我在模型中有一个方法,这导致我的程序无法工作并中断,因为我从产品服务内部的产品评论服务中调用了一个函数,而这个破坏代码的方法是在产品评论模型中.我尝试了一些东西,但它很愚蠢。感谢大家的帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。