0

I am trying to store the JSON data which has been send from the backend (Spring boot application) to the front end (angular). Now everytime I want to store the data in a variable, once I try to access it outside of the subscribe, it will be stored as undefined and will cause errors, I am also working with multiple files and components and I need to pass that data over multiple files.

export class AppComponent implements OnInit {
  routes: RouteItem[] = [];
  public serverMessage = ''; // <=== this is my main variable


  constructor(private http: HttpClient, private routeService: RouteService) {
  }

  ngOnInit() {
    this.http.get('http://localhost:8080/get-json').pipe(
      first(),
      tap(result => console.log('Message received from the server: ', result)),
      map(result => this.serverMessage = (result as any).jsonMessage)
    ).subscribe(data => {
        this.routes = this.routeService.getRoutes(this.serverMessage);
      }
    );
// If I put a console.log(this.serverMessage); here, it wont recognize the data anymore.
  }
}

Can anyone give tips and advise on how to tackle this issue?

  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Jul 12 '22 at 18:53
  • @R.Richards, thanks for your response, I have tried their solutions, but unfortunately it didn't help me solve my problem, I still can't access the data outside of the subscribe scope. – Ghasem Gholi Jul 12 '22 at 19:14
  • Can you explain please when do you get the undefined? in console.log after the subscribe in ngOnInit scope? – ayala Jul 12 '22 at 19:50
  • @ayala Exactly, in console.log after the subscribe, but also in some calls which try to access the variable ```serverMessage```. – Ghasem Gholi Jul 12 '22 at 19:59

1 Answers1

1

You stored the data correctly, the output from the console log is undefined because of java script.
JS execute all synchronous operations before it handles async operation like API calls.

  1. API call is executed.
  2. console.log is executed, the variable is still undefined.
  3. subscribe scope is executed.
  4. the api return a value.
  5. the variable is set.

There are few ways to store and use data from async operations.

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>

ayala
  • 331
  • 1
  • 9
  • Thanks for your explanation, your explanation is clear, but I am confused as to how to solve this, can you give me a push into the right direction? – Ghasem Gholi Jul 12 '22 at 20:03
  • Please add more details in order to understand where you try to use the variable – ayala Jul 12 '22 at 20:04
  • I have one file, which is different from the one I am making this call, in which I parse the data into object members, and another file in which I handle the output into the UI. Both of these files require this variable in order to perform their functions and helpers. I hope this makes sense. – Ghasem Gholi Jul 12 '22 at 20:14
  • i guess your problem is in the implementation of your code. please add more implementation code lines in your question above – ayala Jul 12 '22 at 20:18
  • Try to change your variable to subject, then subscribe to subject changes in order to set your files – ayala Jul 12 '22 at 20:41
  • Tyvm for your help, there are a couple of variables in there which are new, do you have perhaps more context to the code? For example this.dataService, also serverMessage has multiple types. Thanks in advance. – Ghasem Gholi Jul 12 '22 at 23:23