首页 > 解决方案 > 角度:类型上不存在属性“管道”

问题描述

我正在尝试通过单击按钮在 id 上使用 modula 来过滤我的数组。在互联网上搜索我正在使用管道。但我得到一个错误,它“管道”不存在。我不知道为什么?仅仅通过使用 .filter() 而不使用管道是行不通的,而使用它也行不通。或者我只是在一个简单的点击过滤器中走错了方向。我是角度的初学者。

这是我的代码

import { Component, OnInit} from '@angular/core';
import { StreamService } from '../stream.service';
import { Stream } from '../stream';
import { map } from 'rxjs/operators';


@Component({
  selector: 'app-discover',
  templateUrl: './discover.component.html',
  styleUrls: ['./discover.component.scss']
})
export class DiscoverComponent implements OnInit {
  streams!: Stream[];
  
  constructor(private streamService: StreamService) { 
    
  }

  ngOnInit() {
    this.getStreams();
  }

  getStreams(){
    this.streamService.getStream().subscribe((data =>{
      this.streams = data;
      console.log(this.streams);
    }))
  }


  filterIsUneven(){
  this.streams.pipe(map((streams => streams.filter(stream => stream.id % 3)))
  };

}
<div class="container">

  <div class="buttons">
    <button (click) = "filterIsUneven()"> Games </button>
    <button> Music </button>
    <button> Esports </button>
    <button> IRL </button>
    <button>Back</button>
  </div>

  <div class="streams" *ngFor="let stream of streams">
    <h3>{{stream.id}}</h3>
    <h3>{{stream.title}}</h3>
    <img src="{{stream.thumbnailUrl}}">
  </div>

</div>
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Stream } from './stream';
import { Observable} from 'rxjs';
 
@Injectable({
  providedIn: 'root'
})
export class StreamService{

constructor(private http: HttpClient) { }

getStream():Observable<Stream[]>{
  return this.http.get<Stream[]>("https://jsonplaceholder.typicode.com/albums/1/photos");
  }

getLiveStream(id:number):Observable<Stream[]> {
  const url = `https://jsonplaceholder.typicode.com/albums/1/photos?id=${id}`;
  return this.http.get<Stream[]>(url);
  }
}

标签: angulartypescriptpipefiltering

解决方案


当您在 get 流中设置 this.streams 时,this.streams 的类型不是可观察的,而是 Stream[]。因此,当您调用 filterIsUneven() 时,您不能在流上使用 pipe 方法,因为它不是可观察的。而是使用以下逻辑:

filterIsUneven(){
  this.streams.filter(stream => stream.id % 3)
 };

推荐阅读