0

i have mentioned in comments when i console log the selected property with in ngOnInit it does console the object, however outside of this block this when i console this property it is undefined. can some on help how to get it work.. or any other solution

      import { Product } from './../../Models/ProductModel';
        import { Component, OnInit } from '@angular/core';
        // import { Subscription } from "rxjs/Rx";
        import 'rxjs';
        import { Router, ActivatedRoute } from '@angular/router';
        import { ProductService } from 'app/products/product.service';
        @Component({
          selector: 'app-product-detail',
          templateUrl: './product-detail.component.html',
          styleUrls: ['./product-detail.component.css']
        })
        export class ProductDetailComponent implements OnInit {
          public selectedProduct: Product;
          private productIndex: string;
          // private subscription: Subscription;

          constructor(private router: Router,
                      private route: ActivatedRoute,
                      private PService: ProductService) { }

          ngOnInit() {

             this.route.params.subscribe(
              (params: any) => {
                this.productIndex = params['id'];

         }
            );


                this.PService.getProduct(this.productIndex).subscribe((data: any) =>{
                 // return the object
                 console.log(data.product)

               return this.selectedProduct = data.product,
                 //output the here object
                 console.log(this.selectedProduct);

        }

                );

        // output undefined 
                console.log(this.selectedProduct);


          }







this is the getProduct method in my service

    getProduct(id:string){
    const headers = new Headers({ 'Content-Type': 'application/json' });
      return this.http.get('http://localhost:3000/products/'+id, { headers : headers})
      .map((response: Response) => response.json())
      .catch( (error: any) =>
      {

        this.ErS.getError(error.json());
        return Observable.throw(error);
      })



    }
  • 2
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 Jun 22 '17 at 20:34
  • Did you even check the duplicate question with answer? It will always be undefined outside the callback. – AT82 Jun 23 '17 at 09:22
  • thanks . alot.. :) – Mustafa Muhammad Jun 26 '17 at 22:47

1 Answers1

0

I assume that the purpose of this code is reget the data every time the routing parameter changes? If that is correct, then the getProduct call needs to be within the subscribe method.

Like this:

     ngOnInit() {

         this.route.params.subscribe(
          (params: any) => {
             this.productIndex = params['id'];

             this.PService.getProduct(this.productIndex).subscribe((data: any) =>{
             // return the object
             console.log(data.product)

             return this.selectedProduct = data.product,
             //output the here object
             console.log(this.selectedProduct);
            });
     });

           // output undefined 
            console.log(this.selectedProduct);
   }

The last console.log will display an undefined because it is executed when the component is initialized and BEFORE the product is retrieved.

Here is what is happening:

  1. The component is initialized and runs ngOnInit.
  2. The parameter is subscribed to.
  3. The console log at the bottom attempts to display the selected product and there is none ... so undefined.
  4. The change in parameter is processed and the code within the params.subscribe() is executed.
  5. The parameter is obtained from the route and used to call getProduct.
  6. The Observable returned from getProduct is subscribed to.
  7. At some later point, the data is returned from the back-end server and the code within the getProduct().subscribe() is executed.
  8. The two console.logs within the getProduct().subscribe() are executed and display the appropriate product.

Make sense?

DeborahK
  • 57,520
  • 12
  • 104
  • 129