根据路由变量从数组中搜索静态数据?
Search static data from array based on route variable?
我正在尝试在数组中搜索特定对象,该对象具有与数组中的变量匹配的唯一 slug。
在下面的 return 语句末尾尝试使用不带 .valueChanges 的 switchmap 时收到错误消息,但在使用 valuechanges 时我收到错误消息,并说它在 [=20= 上不存在].
组件
post$;
constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }
ngOnInit() {
this.post$ = this.route.paramMap.pipe(
switchMap(params => {
const post = params.get('slug');
return this.nrs.postSearch(post).valueChanges();
})
);
}
这是服务中的函数:
postSearch(slug: string) {
var __FOUND = -1;
for(var i=0; i<this.posts.length; i++) {
if(this.posts[i].postURL == slug) {
// __FOUND is set to the index of the element
__FOUND = i;
break;
}
}
}
我不太确定从这里开始尝试解决这个问题。
我通过将 post 组件更新为此解决了这个问题:
post$: any;
constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }
ngOnInit() {
this.post$ = this.route.paramMap.pipe(
map(params => {
const post = params.get('slug');
return this.nrs.postSearch(post);
})
);
}
并将服务功能更改为:
postSearch(slug: string) {
var __FOUND = -1;
for(var i=0; i<this.posts.length; i++) {
if(this.posts[i].postURL == slug) {
// __FOUND is set to the index of the element
__FOUND = i;
return this.posts[__FOUND];
}
}
}
我正在尝试在数组中搜索特定对象,该对象具有与数组中的变量匹配的唯一 slug。 在下面的 return 语句末尾尝试使用不带 .valueChanges 的 switchmap 时收到错误消息,但在使用 valuechanges 时我收到错误消息,并说它在 [=20= 上不存在].
组件
post$;
constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }
ngOnInit() {
this.post$ = this.route.paramMap.pipe(
switchMap(params => {
const post = params.get('slug');
return this.nrs.postSearch(post).valueChanges();
})
);
}
这是服务中的函数:
postSearch(slug: string) {
var __FOUND = -1;
for(var i=0; i<this.posts.length; i++) {
if(this.posts[i].postURL == slug) {
// __FOUND is set to the index of the element
__FOUND = i;
break;
}
}
}
我不太确定从这里开始尝试解决这个问题。
我通过将 post 组件更新为此解决了这个问题:
post$: any;
constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }
ngOnInit() {
this.post$ = this.route.paramMap.pipe(
map(params => {
const post = params.get('slug');
return this.nrs.postSearch(post);
})
);
}
并将服务功能更改为:
postSearch(slug: string) {
var __FOUND = -1;
for(var i=0; i<this.posts.length; i++) {
if(this.posts[i].postURL == slug) {
// __FOUND is set to the index of the element
__FOUND = i;
return this.posts[__FOUND];
}
}
}