Search code examples
node.jsangularresponsesubscriber

why subscribe method returns Subscriber instead of value in response


In my application User configuration are retrieved based config id which is available in node server .

  exports.getConfig() =(req,res) => {
 return res.status(200).send(id) -> where id is been read from configuration file 
}

In service i have get call that reads property in config file .

      getUserConfig():any {
        this.http.get('/config/user' , {responseType:'text'}).subscribe(data => {
       //console.log(data) ----- prints undefined 
        data
        )
        }

In ts i am storing the user configuration in a variable as follows

let userConfigValue = this.configService.getUserConfig();
//console.log(userConfigValue) --- prints subscriber object

I expected userConfigValue to be "1200" that is the value from file . What am i doing wrong here . How to get the value inside my angular component.


Solution

  • That is not how the RxJS Observable pattern works. Any statements that directly depend on the asynchronous data emitted by the observable (like your assignment to userConfigValue) must be inside the subscription.

    In your case you'd need to return the observable from the call and subscribe where it's response is required.

    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';
    
    getUserConfig(): Observable<any> {    // <-- return `Observable`
      this.http.get('/config/user' , { responseType:'text' }).pipe(
        tap((value: any) => console.log(value))   // <-- use `tap` for side effects (like logging)
      );
    }
    
    userConfigValue: any;
    
    this.configService.getUserConfig().subscribe({
      next: (value: any) => {
        this.userConfigValue = value;
        // other statements that depend on `this.userConfigValue`
      },
      error: (error: any) => {
        // error handling
      }
    });
    

    Next issue: undefined from backend

    This is probably unrelated to the frontend. Make sure the id variable is defined before returning it from the server

    exports.getConfig = (req, res) => {  // <-- parenthesis to `getConfig` isn't required
      console.log(id);  // <-- make sure here it isn't `undefined`
      return res.status(200).send(id);
    }