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")
}
Asked
Active
Viewed 39 times
-3

MoxxiManagarm
- 8,735
- 3
- 14
- 43

vinay kumar
- 1
- 1
-
Observables are not return the data from the subscribe, since it is async operation. You should save the data in a global variable and set the response there – ayala Jul 14 '22 at 09:18
-
1Please format the code correctly. Also add some text on what your problem is and what's not working for you! – cloned Jul 14 '22 at 09:32
-
You cant return a value synchronously from an async call. – MoxxiManagarm Jul 14 '22 at 09:35
1 Answers
0
Set the response in a variable, something like this:
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")
}
)
}
Its much better to return an obseravable in your service, then you have few options for implementation:
- subscribe the obseravable that is returned from the service method . then you can use the response in the subscribe scope or set it in a variable or behevioeSubject:
One of them is to use BehaviorSubject
.
BehaviorSubject is like a property with get and set abilities, plus an extra feature; you can subscribe to it. So whenever there are changes on the property, we will be notified, and we can act on that
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>
- set the observable that is returned from the service method, then you can use async pipe in html in order to display the response in the html. see this example in stackblitz.

ayala
- 331
- 1
- 9
-
-
Maybe this will help you: https://stackoverflow.com/questions/72957059/how-to-store-the-data-to-a-variable-while-performing-subscribe-in-a-http-get-req/72957782#72957782. – ayala Jul 14 '22 at 09:29
-