javascriptangulartypescriptrxjsangular4-httpclient

Variable data not retained to bind in HTML even after assigning data to it inside a subscribe() function


I have below app-product.ts code written as below:

@Component({
   selector: 'app-product',
   template: `
    <div>
      <h2>{{products.prod_name | uppercase}} Details</h2>
      <div><span>Description: </span>{{products.prod_desc}}</div>
    </div>`
 })

export class ProductComponent {

   products:any = [];

   constructor(public rest: RestService){ this.getProducts() }

   getProducts() {
     this.products = [];
     this.rest.getProducts().subscribe((data: {}) => {
     console.log(data); // data is printing in console
      this.products = data; // tried keeping debugger here 
   });
}

In the above code I am able to print the data in console but the variable products is not accessible in my template. I also tried to keep a debugger at the point and I tried to print the products but it was showing as undefined every time.

Below is my angular service file for consuming REST API using Http Client as below:

@Injectable({
  providedIn: 'root'
})

export class CarApiService {

  getProducts(): Observable<any> {
    return this.http.get(endpoint + 'products').pipe(
    map(this.extractData));
  }
}

I also tried to analyse if there is any callback issues in the code but could not figure what is the real cause of this problem.

I also tried looking into few threads like: component variables inside a RxJS subscribe() function are undefined but could not find any help. Can anyone please help me out?


Solution

  • Since the service was in other module i had to create single sharing tree for access that return values. So the code must be placed inside the export shared module block as below:

    static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule
    };
    

    }