gpt4 book ai didi

angular - Angular 7订阅无法正常工作(Angular 7的新增功能)

转载 作者:太空狗 更新时间:2023-10-29 19:36:13 29 4
gpt4 key购买 nike

这里是service employee-service.service.ts的代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IEmployee } from './employee';
import { Observable } from 'rxjs'

@Injectable({
providedIn: 'root'
})
export class EmployeeServiceService {
private _url:string = "/assets/data/employees.json"

constructor(private http: HttpClient) { }
getEmployees(): Observable<IEmployee[]>{
return this.http.get<IEmployee[]>(this._url);
}
}

将typescript代码设置为employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { EmployeeServiceService } from '../employee-service.service';

@Component({
selector: 'app-employee-list',
templateUrl: `<ul *ngFor="let employee of employees">
<li>{{employee.id}}. {{employee.name}} - {{employee.age}}</li>
</ul>`,
styleUrls: ['./employee-list.component.less']
})
export class EmployeeListComponent implements OnInit {
public employees = [];
constructor(private _employeeService: EmployeeServiceService) { }

ngOnInit() {
this._employeeService.getEmployees();
.subscribe(data =>this.employees = data);
}

}

拥有employee.json
[
{"id":1,"name":"A","age":5},
{"id":2,"name":"B","age":4},
{"id":3,"name":"C","age":3},
{"id":4,"name":"D","age":2},
{"id":5,"name":"E","age":1}

]

以及接口employee.ts
export interface IEmployee{
id:number,
name:string,
age:number
}

我正在使用angular 7,angular/cli版本是7.1.0,rxjs版本是6.3.3
我试图创建一个HTTP GET调用来处理JSON中的数据并显示所需的字段。
但是,在使用从“rxjs”导入的可观测数据时。
我看到一个错误显示为“找不到名称订阅”
我该如何处理这个问题呢?因为我已经将rxjs版本更新为rxjs6了?

最佳答案

使用异步管道,不要订阅typescript

import { Component, OnInit } from '@angular/core';
import { EmployeeServiceService } from '../employee-service.service';

@Component({
selector: 'app-employee-list',
templateUrl: `<ul *ngFor="let employee of employees$ | async">
<li>{{employee.id}}. {{employee.name}} - {{employee.age}}</li>
</ul>`,
styleUrls: ['./employee-list.component.less']
})
export class EmployeeListComponent {
public employees$ = this._employeeService.getEmployees();
constructor(private _employeeService: EmployeeServiceService) { }
}

关于angular - Angular 7订阅无法正常工作(Angular 7的新增功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53649403/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com