Angular 2 使用 Http Observable 和 Pipe

标签 angular typescript angular2-http angular2-pipe

我有一个调用 REST 端点的服务:

import { Task } from './task';
import { TaskStatus } from './task-status';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class TaskService {
    constructor(private http: Http){
    }
    getTasks() {
        return this.http.get('http://localhost:8080/tasks').map(res => res.json()).map(rest => rest._embedded.tasks);
    }
}

端点返回如下结果:

{
  "_embedded": {
    "tasks": [
      {
        "title": "zxc",
        "description": "zxc",
        "status": "New",
        "_links": {
          "self": {
            "href": "http://localhost:8080/tasks/1"
          },
          "task": {
            "href": "http://localhost:8080/tasks/1"
          }
        }
      },
      {
        "title": "asd",
        "description": "qweqwe",
        "status": "New",
        "_links": {
          "self": {
            "href": "http://localhost:8080/tasks/2"
          },
          "task": {
            "href": "http://localhost:8080/tasks/2"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/tasks"
    },
    "profile": {
      "href": "http://localhost:8080/profile/tasks"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 3,
    "totalPages": 1,
    "number": 0
  }
}

我使用此组件中的服务:

@Component({
  selector: 'app-mycomp',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
  tasks: Array<Task>;

  constructor(private taskService:TaskService) {
    taskService.getTasks()
    .subscribe(tasks => this.tasks = tasks, 
                err => console.error(err), 
                () => console.log('done'));
  }
}

模板看起来像这样;

<task-details *ngFor="let task of tasks" [task]="task"></task-details>

这按预期工作,但是当我尝试在模板中使用管道时:

<task-details *ngFor="let task of tasks | WithStatus: TaskStatus.New" [task]="task"></task-details>

我收到错误“无法读取未定义的属性“过滤器””。

这是管道实现:

import { Pipe, PipeTransform } from '@angular/core';
import { TaskStatus } from './task-status';

@Pipe({ name: 'WithStatus', pure: true })
export class TaskStatusFilter implements PipeTransform{
    transform(value: any, ...args: any[]): any {
        console.log(value);// value is undefined
        return value.filter(item => item.status == args[0]);
    }
}

最佳答案

在初始更改检测周期中,当 ajax 尚未完成时,它会尝试评估 bindings并通过 tasks值如undefinedWithStatus管道并抛出错误。对于这种情况,您必须仅在管道内处理它。

@Pipe({ name: 'WithStatus', pure: true })
export class TaskStatusFilter implements PipeTransform{
    transform(value: any, ...args: any[]): any {
        console.log(value);// value is undefined
        return (value || []).filter(item => item.status == args[0]);
    }
}

另一种方法是你应该注入(inject) task-details DOM 位于 DOM 树中,直到使用 *ngIf 成功使用 ajax结构指令。

<template [ng-if]="tasks">
  <task-details 
    *ngFor="let task of tasks | WithStatus: TaskStatus.New" 
    [task]="task">
  </task-details>
</template>

而不是 <template>您还可以使用<ng-container>它允许使用与内联 *ngIf 相同的语法:

<ng-container *ngIf="tasks">
  <task-details 
    *ngFor="let task of tasks | WithStatus: TaskStatus.New" 
    [task]="task">
  </task-details>
</ng-container>

关于Angular 2 使用 Http Observable 和 Pipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678104/

相关文章:

linux - : Cannot determine the module for class SomeComponent in/path to that component. ts 中的错误!将 SomeComponent 添加到 NgModule 以修复它

angular - 使用 NPM 安装 Font Awesome 5

reactjs - Mobx 使用参数计算 (compulatedFn) 和 TypeScript - 这是什么?

typescript - 如何定义类型A,其中类型A可以是除类型B之外的任何类型?

angular - 将 Angular 5 中的 Http 升级到 HttpClient : "server responded with a status of 415 (Unsupported Media Type)"

Angular 9 在 UI 上显示变化检测周期数?里面的stackblitz

angular - 在组件之间展开/折叠功能

javascript - 如何根据相同的键名在枚举之间进行映射?

angular - 在 Angular2 的英雄之旅中找不到模块 './in-memory-data-service'

javascript - 如何使用 javascript 使用 angular 2 http post 函数提交表单?