问题描述: 在Angular 7中,当我尝试在可观察对象中访问服务时,返回的值为undefined。
解决方法:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable()
export class MyService {
getData(): Observable {
// 这里返回一个可观察对象
return of({ name: 'John', age: 30 });
}
}
import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
template: `{{ data | json }}`,
})
export class MyComponent implements OnInit {
data: any;
constructor(private myService: MyService) {}
ngOnInit() {
this.myService.getData().subscribe((result) => {
this.data = result;
});
}
}
通过以上两个步骤,你应该能够在可观察对象中正确地访问服务并得到返回的值。