Home > Mobile >  TypeScript Define an Array
TypeScript Define an Array

Time:12-06

im new to TS and wondering how to make this work,

products: any;

ngOnInit() {
        this.productService.getProducts().subscribe(data => this.products = data);
        console.log(this.products)
    }

By declaring products "any" this works just fine but products is undefined. Later in the code i will need products to be defined becouse of this ERROR TypeError: Cannot read properties of undefined (reading 'trim').

So i tried this

products = new Array<Object>();

ngOnInit() {
       this.productService.getProducts().subscribe(data => this.products = data);
       console.log(this.products)
   }

this says that Type 'Object' is not assignable to type 'Object[]'

another try

products: { id: number, cislo: string, nazov: string}[];

ngOnInit() {
        this.productService.getProducts().subscribe(data => this.products = data);
        console.log(this.products)
    }

this follows with

Property 'products' has no initializer and is not definitely assigned in the constructor.

what way sould i declare products so they will be defined?

.... EDIT

getProducts looks like

getProducts() {
        return this.http.get('http://localhost:8080/zakon/getAListOfAll');
    }

and it returns this json

[
  {
    "id": 0,
    "cislo": "0/0",
    "nazov": "bez zakona"
  },
  {
    "id": 1,
    "cislo": "156/25",
    "nazov": "zakon 165 o niecom z roku 123"
  },
  {
    "id": 2,
    "cislo": "222/22",
    "nazov": "zakon 166 o niecom z roku 1234"
  }
]

CodePudding user response:

    export interface Product : { 
    id: number, 
    cislo: string,
     nazov: string
    }
    //@Component....
    
    products:Product[]=[]
    
    ngOnInit() {
             this.getProducts()  
        
               
            }

getProducts(){
this.productService.getProducts().subscribe(
        (data:Product[] )=> {
         this.products = data
         console.log(this.products)
        })
}

CodePudding user response:

products: { id: number, cislo: string, nazov: string}[];

ngOnInit() {
    this.productService.getProducts().subscribe(data => {
      this.products = data;
      console.log(this.products);
    });
}

You are accessing products outside the callback function. As it will log this.products like a static code here where the api call is async. Try it this way and access it inside the callback function.

  • Related