根据路由变量从数组中搜索静态数据?

问题描述 投票:0回答:1

我试图在一个数组中搜索一个特定的对象,这个对象有一个唯一的slug,它与数组中的一个变量相匹配.当我试图在下面返回语句的结尾处使用不带.valueChanges的switchmap时,我收到了一个错误,但是当我使用valuechanges时也收到了一个错误,说它在 "类型'void'"上不存在。

组件

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;
            }
        }
  }

我不知道该从哪里着手解决这个问题。

angular typescript angular-routing angular-router
1个回答
0
投票

我通过更新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];
            }
        }
  }
© www.soinside.com 2019 - 2024. All rights reserved.