如果在Angular 7中返回的Observable不起作用,可以尝试以下解决方法:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
return
关键字返回Observable对象。import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class DataService {
constructor(private http: HttpClient) {}
getData(): Observable {
return this.http.get('url').map(response => response.json());
}
}
ngOnInit
方法中订阅服务中返回的Observable。import { Component, OnInit } from '@angular/core';
import { DataService } from 'path-to-data-service';
@Component({
selector: 'app-my-component',
template: '...',
})
export class MyComponent implements OnInit {
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getData().subscribe(
data => {
// 处理数据
},
error => {
// 处理错误
}
);
}
}
通过这些步骤,你应该能够在Angular 7中正确地返回Observable并订阅它们。