[英]angulars 4 promise service
I have created a service to use some datas. 我已经创建了一项使用某些数据的服务。 IT works perfectly.
IT完美运行。 The problem is that I would like to apply a pipe on these datas in my hTML template to sort them.
问题是我想对hTML模板中的这些数据应用管道以对其进行排序。 here is my component
这是我的组件
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import {AlimentsService} from '../services/aliments.service';
import {AlimentsModel} from '../datas/aliments-model';
@Component({
selector: 'app-liste',
templateUrl: './liste.component.html',
styleUrls: ['./liste.component.css'],
providers: [AlimentsService]
})
export class ListeComponent implements OnInit {
t_aliments: AlimentsModel[];
aliments:AlimentsModel;
constructor(private alimentservice: AlimentsService) {
}
getAliments():void{
//on utilise une promise pour obtenir tous les aliments si on les obtiens on les passent en parametre d'une fonction qui les affecera à notre t_aliments
this.alimentservice.getAliments().then(t_aliments => this.t_aliments=t_aliments);
console.log(this.t_aliments);
}
ngOnInit(): void {
this.getAliments();
}
}
here is my pipe 这是我的烟斗
import {Pipe, PipeTransform} from '@angular/core';
import {AlimentsModel} from '../datas/aliments-model';
@Pipe ({
name:'sort_aliments'
})
export class AlimentsSortPipe implements PipeTransform {
transform(value:AlimentsModel[], args:string):any{
if (args==='ascending')
{
value.sort(function(a,b){
var nameA = a.nom.toUpperCase(); // ignore upper and lowercase
var nameB = b.nom.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
else if(args==="descending")
{
value.sort(function(a,b)
{
var nameA = a.nom.toUpperCase(); // ignore upper and lowercase
var nameB = b.nom.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return 1;
}
if (nameA > nameB) {
return -1;
}
// names must be equal
return 0;
});
}
}
}
and here is my tempalte html 这是我的tempalte html
<div *ngFor="let aliment of t_aliments | sort_aliments:'ascending'" class="list-group">
<a href="#" class="list-group-item ">
{{aliment.nom}} <br>{{aliment.quantite}}
</a>
</div>
My error message is that sort can be applied on undefined ...As if my t_aliments was not existing.... But it exists If I can use it without the pipe... 我的错误消息是可以对未定义的对象应用排序...好像我的t_aliments不存在....但是如果我可以在没有管道的情况下使用它,它就存在...
可以,我直接对数据服务进行了排序...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.