Array of data retrieved from a response

0

I have a rest service that returns macs from a scan, the json model 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 following files:

mac.component

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.component

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 in 'macs' it comes as undefined, I need an array of return macs

    
asked by anonymous 10.08.2017 / 17:59

1 answer

1

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

In addition, 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 return an array directly 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 to the console.log within the getMacs () method will always return null (if it is never initialized), because it must be 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) 
  );

}

    
10.08.2017 / 20:53