import { Injectable } from '@angular/core';
import { SearchService } from 'src/app/services/search/search.service';
@Injectable()
export class ManageFlightBookHoldService {
constructor(
private flight_search: SearchService,
) { }
getBookHoldflightData (id:number) {
let flight = this.flight_search.getFlightAdmin(id).subscribe(
function(response){ return (response)}
)
console.log(flight, "fghjk")
}
在一个变量中设置响应,如下所示:
import { Injectable } from '@angular/core';
import { SearchService } from 'src/app/services/search/search.service';
@Injectable() export class ManageFlightBookHoldService {
responseData:any;
constructor( private flight_search: SearchService) { }
getBookHoldflightData (id:number) {
this.flight_search.getFlightAdmin(id).subscribe((response)=>
{
this.responseData=response; //store the data in a variable
console.log(this.responseData, "fghjk")
}
)
}
在你的服务中返回一个可观察对象要好得多,这样你的实现选项就很少了:
- 订阅从service方法返回的可观察对象。然后您可以使用订阅的响应作用域或在变量或行为中设置它:
其中之一是使用BehaviorSubject
BehaviorSubject就像一个具有get和set能力的属性,加上一个额外的功能;你可以订阅它。所以当属性发生变化时,我们就会收到通知,然后我们就可以对
进行操作了
TS:
constructor(private http: HttpClient) {
this.serverMessageSubject= new BehaviorSubject<any>(null);
}
serverMessageSubject: BehaviorSubject<any>;
serverMessage$:Observable<any>;
ngOnInit(): void {
this.getData();
this.serverMessage$= this.serverMessageSubject.asObservable();
this.serverMessage$.subscribe((result)=>
{
console.log("here you can set your files etc...",result)
})
}
getData() {
this.http
.get<any>('http://localhost:8080/get-json')
.pipe(
tap((result) => {
this.serverMessageSubject.next(result);
})
)
.subscribe((data) => {
});
}
HTML:
<div>{{ serverMessage$ | async | json }}</div>
- 设置从service方法返回的可观察对象,然后你可以在html中使用async pipe来显示响应。