这是一个简单的Angular 2课程,我使用:
public class LogEntry
{
public int id { get; set; }
public string company { get; set; }
public string name { get; set; }
}
使用.map
中的http.get
绑定哪些数据:
export class LogService {
constructor( @Inject(Http) private http: Http) {}
...
return this.http.get(myGlobals.API_URL).map(this.extractData)
...
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
以下是调用LogService类(log.component.ts)的组件代码:
import { Component, OnInit } from '@angular/core';
import { LogEntry } from './log';
import { LogService } from './log.service';
@Component({
moduleId: module.id,
selector: 'log-list',
templateUrl: './log-list.component.html',
providers: [ LogService ]
})
export class LogListComponent implements OnInit {
errorMessage: string;
logEntries: LogEntry[];
mode = 'Observable';
constructor (private LogService: LogService) {}
ngOnInit() { this.getLog(); }
getLog() {
this.logService.getLog()
.subscribe(
logs=> this.logEntries = logs,
error => this.errorMessage = <any>error);
}
}
以下是我用来显示数据的HTML模板:
<div *ngFor="let logEntry of logEntries" class="row">
<div class="cell">{{logEntry.id}}</div>
<div class="cell">{{logEntry.company}}</div>
<div class="cell">{{logEntry.name}}</div>
</div>
现在让我们说我想在HTML中显示之前操纵数据。
例如:我想trim()
或replace()
为logEntry.name
返回的字符串 - 没有为每个字符串创建管道的麻烦的操作。
这可能吗?
谢谢大家。
答案 0 :(得分:1)
你可以使用过滤器并做任何修改,
getLog() {
this.logService.getLog()
.subscribe(
logs=> this.logEntries = logs,
error => this.errorMessage = <any>error);
this.logEntries = this.logEntries.filter(element => {
return element.name.trim();
});
}