首页 > 解决方案 > 想用管道返回新的可观察对象,每次都传入新数据。使用 Angular 6

问题描述

我有一个 get 方法,它从 API 中检索数据,其值每分钟都在变化。这些数据每分钟都需要与静态数据相乘并显示给用户。我决定使用管道来处理此事务,因为此数据将在整个应用程序本身中频繁使用。

我的问题是,在实现此管道时,在循环中运行时,它会采用管道输入的最后一个静态值,并为所有已通过的值更改它。

我想要传递的单个静态值的相乘值。并作为可观察对象返回 UI。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private service: AppService,private http: HttpClient) {}
  private fetchDataTemp$: Observable<any>;

  private killTrigger: Subject<void> = new Subject();

  private refreshIntervalTemp$: Observable<any> = timer(0, 60000)
    .pipe(
      // This kills the request if the user closes the component 
      takeUntil(this.killTrigger),
      // switchMap cancels the last request, if no response have been received since last tick
      switchMap(() => this.fetchDataTemp$),
      // catchError handles http throws 
      catchError(error => of('0'))
   );

  getData() {
    return this.http.get("https://jsonplaceholder.typicode.com/posts/42")
      .pipe(
        retry(3),
        share()
      );
  }

  public tempdata$: Observable<any> = this.refreshIntervalTemp$;
  fakedata = [1,2,3];

  ngOnInit() {  
    this.fakedata.forEach(element => {
      this.tempdata$.subscribe(data => { console.log(data,"test"); }); 
      console.log(element);  

      this.fetchDataTemp$ = this.getPrice().pipe(
        map(
          (response) => {
            console.log(element*response.id as number)
            return response.id;
          },
          share()
        )
      ); 
    });
  }
}

上面的代码与我想要实现的场景非常相似。是fakedata传递到管道中的数据,foreach是异步运行的 ngFor 循环。在这种情况下, urlhttps://jsonplaceholder.typicode.com/posts/42 返回静态数据,因此我能够保持数据一致response.id is 42。运行此代码时,结果是

1
2
3
126 test 
126 test 
126 test  

我期望的是

 1
 2
 3
 42 test
 84 test
 126 test

我指出了这个问题,map()但我不知道如何强制地图一次处理一个值并相应地返回它们。

提前致谢!

标签: angulartypescriptdictionaryangular2-observablesangular-pipe

解决方案


推荐阅读