TypeError, I can not map json to model. Angular 4

0

I am making a form to create an account and I am faced with the following problem.

The first thing I do is go to find the json to an api that at the moment I have the json locally in assets,

This is the method of the service that is responsible for searching the json

getJoinCustomer():Observable<JoinCustomer>{
  return this.http
        .get(this._url).pipe(
          map((res:Response)=>res.json())
        )
}

Then in my component I inject the service and I call it within a method to map it to my property.

  getJoinCustomer():void{
    this._joinService.getJoinCustomer()
    .subscribe(joinCustomer => {
          this.joinCustomer = joinCustomer;
                     this.join = new Join(this.joinCustomer.customerID)                              
          })

And I call this method from the

ngOnInit(){
this.getJoinCustomer();
}

And even if I made the model in the following way

    {"joinCustomer":[{
   "customerID":"ASD123"
   }]}

JSON

    export class JoinCustomer{
   customerID:string;
   }

JoinCustomer.ts

I get the error

  

TypeError: Can not read property 'customerID' of undefined

    
asked by PCH 09.05.2018 в 21:03
source

2 answers

2

This happens to you because in the function:

  getJoinCustomer():void{
    this._joinService.getJoinCustomer()
    .subscribe(joinCustomer => this.joinCustomer = joinCustomer)

    console.log(this.joinCustomer.customerID) //this is TypeError
  }

you use the joinCustomer property outside the subscribe so it is probably undefined at this time, since it is an asynchronous call and it may take X time to skip the subscribe.

If you want to show by console that it brings you the data correctly, it would be like this:

  getJoinCustomer():void{
    this._joinService.getJoinCustomer()
    .subscribe(joinCustomer => {

         this.joinCustomer = joinCustomer
         console.log(this.joinCustomer.customerID) //this is TypeError
    })


  }
    
answered by 09.05.2018 / 21:13
source
0

{"joinCustomer": [ {    "customerID": "ASD123"    } ] }

The reason why the error comes out is because you can not access an element that is inside an array or list in that way, it would be like this: this.joinCustomer [0] .customerID

    
answered by 09.05.2018 в 22:23