Apologies for my English.
I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods.
Within my provider, I have the following code:
Provider:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class UserServiceProvider {
path : string = 'my_paht_remote';
constructor(public http: HttpClient) {
console.log('Hello UserServiceProvider Provider');
}
getUsers() {
return this.http.get(this.path');
}
getList()
{
return new Promise ( resolve => {
this.http.get(this.path).subscribe(
data => {
resolve(data);
}, err => {
console.error();
}
);
} );
}
}
Now, in the TypeScript file:
--Imports
...
import { UserServiceProvider } from '../../providers/user-service/user-service';
...
export class CaicesPage {
users: any;
users2: any;
...
ionViewDidLoad()
{
this.showMap(); //This is a function for viewing Google Maps.
}
showMap()
{
//Here I should be able to see the result of the remote JSON File:
this.userService.getUsers().subscribe(
(data) => { // Success
this.users = data['results'];
},
(error) =>{
console.error(error);
}
);
console.info(this.users); // I am seeing 'Undefined', Why ?
//With the following approach, I can also view the contents of the JSON File:
this.userService.getList().then(
data => {
this.users2=data['results'];
}
);
console.info(this.users2); // Again, I see 'Undefined', Why ?
}
}
How can I access the values of var users or var users2 outside of subscribe or then functions?
Your assistance is greatly appreciated.