Angular 5 Pipe - 用名称替换实体id

时间:2018-02-15 08:25:07

标签: angular caching pipe observable angular5

我需要使用管道将类别ID转换为Angular 5组件中的名称 - 我在下面给出了管道代码:

import { Pipe, PipeTransform, Injectable } from '@angular/core';
import { CategoriesResourceService } from '../apiResources/categories-resource.service';
import { Category } from '../models/category.model';
import { HttpClient } from '@angular/common/http/src/client';

@Pipe({ name: 'categoryPipe', pure: false })
@Injectable()
export class CategoryNamePipe implements PipeTransform {

  private cachedData: Category[];

  constructor(private http: CategoriesResourceService) { }

  transform(value: number): any {

    if (this.cachedData != null) {
      return this.findCachedItemById(value);
    }

    this.http.get(null)
      .map(result => result)
      .subscribe(result => this.cachedData = result);

    return this.findCachedItemById(value);
  }

  findCachedItemById(value: number) {
    if (this.cachedData == null || this.cachedData.length === 0) { return ''; }
    for (const item of this.cachedData) {
      if (item.categoryId === value) {
        return item.name;
      }
    }
    return '';
  }
}

并在下面的组件中使用它:

<tr *ngFor="let task of tasks">           
    <td>{{task.categoryId | categoryPipe}} - {{task.subcategoryId  | categoryPipe}}</td>
</tr>

我想实现我将类别ID传递给管道并从API(从数据库)获取类别并返回其名称 - 即使它不在cachedData中,然后只从cachedData获取它并且不发送API请求。 / p>

我的问题是我无法缓存数据,它将200个HTTP请求发送到类别API,用于此管道的5个用法(5行表)。

你能否给我一些建议如何做或帮我修理我的代码?

THX

1 个答案:

答案 0 :(得分:0)

不要在管道中进行HTTP调用。

相反,在应用程序组件中进行一次HTTP调用(将在应用程序启动时启动),并根据需要存储数据(localStorage,自定义服务...)。

一旦你拥有它,让我们说在服务中,管道变得易于使用:

transform(value: number): any {

  if (!this.myService.cachedData) { return 'Data is not cached (put your own message there)'; }

  return this.myService.cachedData.find(item => item.categoryId === value) ?
    this.myService.cachedData.find(item => item.categoryId === value).name :
    'No cached data found (put your own message there)';
}