Array of recovered data from a Response

Asked

Viewed 398 times

0

have a service Rest q returns Macs coming from a scan,the json template and this:

{
"macs": [
    {
        "mac": "9C:5C:F9:66:73:34"
    },
    {
        "mac": "B8:A3:E0:72:9E:EA"
    },
    {
        "mac": "00:E0:4C:2A:26:60"
    },
    {
        "mac": "00:E0:4C:76:0A:A7"
    },
    {
        "mac": "00:E0:4C:0D:C7:58"
    },
    {
        "mac": "00:E0:4C:79:7A:17"
    },
    {
        "mac": "00:E0:4C:07:72:D9"
    },
    {
        "mac": "00:E0:4C:60:97:77"
    }
  ]
}

I have the files:

mac.

export class MacComponent implements OnInit {
@Input() mac:Mac
constructor() { }

 ngOnInit() {
  }

 }

mac model.

export interface Mac{
mac:string
}

mac service.

@Injectable()
 export class MacService {

 constructor(private http: Http) { }

 getMacs():Observable<Mac[]>{
 return this.http.get('http://localhost:3000/macs')
 .map(response => response.json())

  }

 }

Macs.

export class MacsComponent implements OnInit {
macs:Mac[]
constructor(private service:MacService) { }

ngOnInit() {
    this.getMacs()
}
getMacs(){
    this.service.getMacs().subscribe(macs => this.macs = macs)
    console.log(this.macs);

}
printMacs(){
    console.log(this.macs);

}
} 

when I print the 'Macs' it comes as Undefined, I need an array of return Macs

1 answer

1


The call to service is correct. But it may have failed, and so you did not have an object of return. Look in the browser console if the call was successful, the error being from CORS.

Also, the return of your API is not an array, but an object that has a member (Macs) that is an array. You need to update your API to directly return an array or update the API call, as below:

@Injectable()
 export class MacService {

 constructor(private http: Http) { }

 getMacs():Observable<Mac[]>{

      return this.http.get('http://localhost:3000/macs')
       .map(response => response.json())
       .map(jsonRet => jsonRet.macs);

  }

 }

Your call from the console log. within the getMacs() method, it will always return null (if it is never initialized), because it should stay inside the subscribe, since the call is always asynchronous, see:

getMacs(){
  this.service.getMacs().subscribe(macs => {

      this.macs = macs;
      console.log(this.macs);

    }, error => console.log('ocorreu um erro na chamada', error) 
  );

}

  • I tried this and gave this error Property 'Macs' does not exist on type 'Mac[],I tried to change interface to class but remained the same

  • Try right, Typscript will give error even. This, because your Observable is of type Observable<mac[]>. My suggestion was by the return of your API, had not paid much attention in the return of the observable. I will update my reply.

  • worked, thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.