简体   繁体   English

angular2 pipe 不工作 - 没有错误

[英]angular2 pipe not working - no errors

I have a service that returns a list of pages.我有一个返回页面列表的服务。 Now I want to write a pipe named pagesFilter that returns a list of pages that has this key set as true.现在我想编写一个名为 pagesFilter 的 pipe,它返回一个将此键设置为 true 的页面列表。

Then I want to apply this filter when clicking on a navigation item.然后我想在单击导航项时应用此过滤器。

Somehow I can't get it to work.不知何故,我无法让它工作。 There are no errors in the console, and the filter variable gets updated correctly.控制台中没有错误,并且过滤器变量得到正确更新。 Any advice is appreciated.任何建议表示赞赏。

My html:我的 html:

<!-- portfolio submenu -->
<div id="portfolioMenu">
    <div id="portfolioMenuOrangeLine"></div>
    <div id="filter1" class="miniNavButton" (click)="changeFilter('app demos')">
        <a>
            <svg class="icon icon-eye">
                    <use xlink:href="symbol-defs.svg#icon-eye"></use>
                </svg>
        </a>
    </div>
    <div id="filter2" class="miniNavButton" (click)="changeFilter('github repos')">
        <a>
            <svg class="icon icon-embed">
                    <use xlink:href="symbol-defs.svg#icon-embed"></use>
                </svg>
        </a>
    </div>
    <div id="filter3" class="miniNavButton" (click)="changeFilter('work in progress')">
        <a>
            <svg class="icon icon-hammer">
                    <use xlink:href="symbol-defs.svg#icon-hammer"></use>
                </svg>
        </a>
    </div>
</div>

<h2 class="filterHeading">Showing: {{ filter }}</h2>

<!-- portfolio content -->
<div class="portfolioContainer">
    <div class="displayHack"></div>
    <div *ngFor="#p of pages" class="portfolioPageContainer">
        <img [attr.src]="p.img" class="portfolioThumbnail">
        <h2>{{ p.name }}</h2>
        <a [attr.href]="p.repo">
            <div>
                <p>{{ p.description }}</p>
            </div>
            <p class="portfolioRepoLink">See the Code!</p>
        </a>
    </div>
    <div class="displayHack"></div>
</div>

pages service:页面服务:

import { Injectable } from 'angular2/core';

export class Page {
    constructor(public img: string, public name: string, public repo: string, public description: string, public demo: boolean, public github: boolean, public finished: boolean) { }
}

@Injectable()
export class PagesService {
    getPages() {
        return [
            new Page('./app/images/placeholder.png', 'veryNiceWords', 'https://github.com/Shooshte/veryNiceWords', 'A hobby app, made to enable posting, rating and sharing quotes over social networks. Work in progress.', false, true, false),
            new Page('./app/images/placeholder.png', 'ZIC IJS', 'https://github.com/Shooshte/ZIC', 'Refurbishing of on old library webpage with AngularJS.', false, true, false),
            new Page('./app/images/weather.png', 'Show the Local weather', 'http://codepen.io/shooshte/pen/NxOwOX', 'A freeCodeCamp exercise, designed to show the local weather.', true, false, true),
            new Page('./app/images/calculator.png', 'Calculator', 'http://codepen.io/shooshte/pen/qbjJdy', 'A freeCodeCamp exercise, which requires you to build a javascript calculator.', true, false, true),
            new Page('./app/images/github.png', 'MTGO Draft Replayer', 'https://github.com/Shooshte/MTGO-Draft-Replayer', 'A simple web app that opens a MTGO draft log file, and re-creates the draft from it.', false, true, false),
            new Page('./app/images/codeeval.png', 'codeEval', 'https://github.com/Shooshte/CodeEval', 'CodeEval challenges solutions written in javascript and posted to gitHub.', false, true, true)
        ];
    }
}

portfolio component (that uses the service):投资组合组件(使用服务):

import { Component } from 'angular2/core';
import { ViewEncapsulation } from 'angular2/core';
import { Page, PagesService } from './pages.service';
import { Pipe, PipeTransform } from 'angular2/core';

@Pipe({ name: 'filter' })
export class pagesFilter {
    transform(pages, [key]): string {
        return pages.filter(page => {
            return page.hasOwnProperty(key);
        });
    }
}

@Component({
    selector: 'portfolio',
    templateUrl: '/app/views/portfolio.html',
    styleUrls: ['../app/styles/PortfolioMobile.css', '../app/styles/PortfolioOther.css'],
    pipes: [pagesFilter],
    encapsulation: ViewEncapsulation.None
})

export class PortfolioComponent {
    filter = 'everything';

    filterPortfolio(parameter:String) {
        return this.pages ? 'pagesFilter' : parameter
    }

    changeFilter(x) {
        this.filter = x;

        if (x == 'app demos') {
            this.filterPortfolio('demo');
        }
        else if (x == 'github repos') {
            this.filterPortfolio('repo');
        }
        else if (x == 'miniNavButton') {
            this.filterPortfolio('finished');
        }
    }

    pages: Page[];

    constructor(private _pagesService: PagesService) { }

    ngOnInit() {
        this.pages = this._pagesService.getPages();
    }

}

Before using the Pipe inside a component you need to add it inside pipe option of that component MetaData. 在组件内部使用Pipe之前,您需要在该组件MetaData的pipe内部选项中添加它。

@Component({
    selector: 'portfolio',
    templateUrl: '/app/views/portfolio.html',
    styleUrls: ['../app/styles/PortfolioMobile.css', '../app/styles/PortfolioOther.css'],
    pipes: [pagesFilter], //add pipe here
    encapsulation: ViewEncapsulation.None
})

You need to provide a parameter to the pipe: 您需要为管道提供参数:

@Pipe ({
  name:'filter'
})
export class FilterPipe {
  transform(value, params) {
    var filter = params[0];

    return value.filter((item)=> {
      // for example
      return (item.name === filter);
    });
  }
}

You can use this pipe this way basing on a form input and a component property: 您可以根据表单输入和组件属性以这种方式使用此管道:

@Component({
  (...)
  template: `
    <form>
      <input [ngFormControl]="ctrl"/>
    </form>

    <div *ngFor="#elt of elements | filter:filterValue">{{elt.name}}</div>
  `,
  pipes: [ FilterPipe ]
})
export class MyComponent {
  filterValue:string;
  ctrl:Control;

  contructor() {
    this.control = new Control();
    this.control.values.debounceTime(500).subscribe(
      (data) => {
        this.filterValue = data;
      }
    );
  }
}

Edit 编辑

You could also update filterValue on click events: 您还可以在点击事件上更新filterValue

@Component({
  (...)
  template: `
    <div (click)="updateFieldValue('new value')">
      Update
    </div>

    <div *ngFor="#elt of elements | filter:filterValue">{{elt.name}}</div>
  `,
  pipes: [ FilterPipe ]
})
export class MyComponent {
  filterValue:string;

  updateFilterValue(newValue) {
    this.filterValue = newValue;
  }
}

I was facing the same issue.我面临着同样的问题。 Pipe was perfect no errors in console. Pipe 在控制台中非常完美,没有错误。 I resolved it by stopping current ng serve and re-running it.我通过停止当前的ng serve并重新运行它来解决它。 The issue is, when ever you add a pipe, It is also added to modules.问题是,当您添加 pipe 时,它也会添加到模块中。 ng serve mostly doesn't detect changes in modules. ng serve大多不检测模块的变化。 So you have to re-run ng serve .所以你必须重新运行ng serve Might be helpful.可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM