角度2 - 无法找到管道

时间:2017-01-28 17:01:42

标签: angular angular2-pipe

我试图将我的自定义管道用于我在订阅中分配值的数组。但是我收到了这个错误:

Unhandled Promise rejection: Template parse errors:
The pipe 'summary' could not be found

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'
import { HttpModule } from '@angular/http'
import { AppComponent }  from './app.component';
import { UserComponent }  from './components/user.component';
import { AboutComponent }  from './components/about.component';
import { routing }  from './app.routing';
import { SummaryPipe } from './pipes/summary.pipe'

@NgModule({
  imports:      [ BrowserModule, FormsModule, HttpModule, routing ],
  declarations: [ AppComponent, UserComponent, AboutComponent, SummaryPipe ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

summary.pipe.ts

import { Pipe, PipeTransform } from '@angular/core'

@Pipe({name: 'summary'})
export class SummaryPipe implements PipeTransform{
    transform(value: string, args: String[]){
        if(value)
            return value.substring(0, 50) + "...";
    }
}

user.component.ts

import { Component } from '@angular/core';
import { PostsService } from '../services/posts.services';

@Component({
    moduleId: module.id,
    selector: 'user',
    templateUrl: 'user.component.html',
    providers: [PostsService],

})
export class UserComponent  { 
  name: String;
  email: string;
  address: address;
  hobbies: string[];
  showHobbies: boolean;
  posts: Post[];

  constructor(private postsService: PostsService){
    this.name = 'John Doe';
    this.email = 'john@gmail.com';
    this.address = {
        street: '12 Main st',
        city: 'Boston',
        state: 'MA'
  }
  this.hobbies = ['Music', 'Movies', 'Sports']
  this.showHobbies = false;

  this.postsService.getPosts().subscribe(posts => {
      this.posts = posts;
  })

 }

  toggleHobbies(){
     if(this.showHobbies)
     this.showHobbies = false;
     else
     this.showHobbies = true;
 }

 addHobby(hobby){
     this.hobbies.push(hobby);
 }

 deleteHobby(index){
     this.hobbies.splice(index, 1);
 }
}

 interface address{
     street: string;
     city: string;
     state: string;
 }

interface Post{
    id: number;
    title: string;
    body: string;
}

user.component.html

<h3>Posts</h3>
    <div  *ngFor="let post of posts">
        <h3>{{post.title }}</h3>
        <p>{{post.body | summary}}</p>
    </div>

我已经按照文档进行了操作,但我似乎无法使用它。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

转换函数decleration应该返回一些值。在您的案例字符串中。

转换函数看起来应该是这样的:

  transform(value: string): string {
     if(value){
        return value.substring(0, 50) + "...";
     }
     return value;
  }