因为我正在学习和理解角度2我正面临着这个问题。我有一个提供http get请求的服务。
import { Injectable } from '@angular/core';
import { Http, Response, } from '@angular/http';
import { Observable } from 'rxjs/Rx'
import { LanguagesResponse } from '../shared/model/languages/languages-response';
@Injectable()
export class HttpLanguageService {
constructor(private http: Http) { }
getLanguages(): Observable<LanguagesResponse> {
return this.http.get('http://192.168.99.100:8888/em-deployer/ws/languages?pretty=true&expand=true').map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body || {};
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
我有一个组件负责获取服务的结果并将其放入模板中。 (ngFor)
import { Language } from "../shared/model/languages/language";
import { HttpLanguageService } from '../http-services/http-language.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-iate-quick-mode',
templateUrl: './quick-mode.component.html',
})
export class QuickModeComponent implements OnInit {
languages: Language[];
errorMessage: string;
sourceNonEuLanguages: boolean = true;
targetNonEuLanguages: boolean = true;
constructor(private httpLanguageService: HttpLanguageService) {
}
ngOnInit() {
this.getLanguages();
console.log(this.languages);
}
getLanguages() {
this.httpLanguageService.getLanguages()
.subscribe(
(languages) => {
this.languages = languages.items;
console.log(this.languages);
},
error => this.errorMessage = <any>error,
);
}
}
自定义管道,它将根据返回数组的布尔值返回一些结果。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'languagesFilter'
})
export class LanguagesFilterPipe implements PipeTransform {
transform(items: any[], arg: boolean): any {
return items.filter(item => item.is_official == arg);
}
}
我的模板
<div>
<dl class="EU-languages">
<dd class="language EU-lang"
*ngFor="let language of (languages | languagesFilter:true)">
<input type="radio"
id="{{language.code}}" />
<label htmlFor="{{language.code}}"> {{language.code | uppercase}}</label>
</dd>
</dl>
</div>
当我不使用管道时,一切正常,我将所有数组对象填充并显示在模板中。当我使用管道时,我收到以下错误=&gt;引起:无法读取未定义的属性“过滤器”。 我将数组更改为具有初始化数组的数组,并且管道正常工作。 有什么建议?我错过了什么?
答案 0 :(得分:0)
这是因为第一次调用管道时,还没有列表/数组..
像这样更改管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'languagesFilter'
})
export class LanguagesFilterPipe implements PipeTransform {
transform(items: any[], arg: boolean): any {
if (!items || !items.length) return [];
return items.filter(item => item && item.is_official == arg);
}
}
您可以像这样启动您的本地变量:
languages: Language[] = [];
..但修改过的Pipe应该有助于解决任何其他问题&#34;错误&#34;太!