以下是一个使用Angular 8从服务返回对象,排序并显示的解决方法的代码示例:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Alice' },
{ id: 3, name: 'Bob' },
{ id: 4, name: 'David' }
];
getData() {
return this.data;
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-data',
template: `
Sorted Data:
- {{ item.id }} - {{ item.name }}
`
})
export class DataComponent implements OnInit {
sortedData: any[];
constructor(private dataService: DataService) { }
ngOnInit() {
const data = this.dataService.getData();
this.sortedData = data.sort((a, b) => a.name.localeCompare(b.name));
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { DataComponent } from './data.component';
import { DataService } from './data.service';
@NgModule({
declarations: [
AppComponent,
DataComponent
],
imports: [
BrowserModule
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
Angular 8 - Sorting and Displaying Data
`
})
export class AppComponent { }
Angular 8 - Sorting and Displaying Data
这样就可以从服务返回对象,对数据进行排序,并在页面中显示排序后的数据了。