Reputation: 23
I am triying yo save data using angular service like this :
@Injectable()
export class DataServiceProvider {
url;
jsonArr = [];
constructor(public http: Http) {
this.url='assets/data/userProfiles.json';
}
getProfiles(){
return new Promise(resolve => {
this.http.get(this.url).
subscribe(data => {
resolve(data.json());
}, err => {
console.log(err);
});
});
}
proccessProfiles(){
this.getProfiles().then(
data=>{
data[0].companies.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "company"
});
})
data[1].centers.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "center"
});
})
}
)
}
}
when i called in my app.component.ts:
I've imported this :
import {DataServiceProvider} from '../providers/data-service/data-service';
and in this function I call:
openPopup(){
console.log('Openpopup ');
this.modalCtrl.create(ProfilePage).present();
this._ds.proccessProfiles();
}
It return error :
Cannot read property jsonArr of undefined
Do you someone how can i solve that ?
Thank you
Upvotes: 0
Views: 120
Reputation: 50291
Try by binding this
proccessProfiles(){
this.getProfiles().then(
data=>{
data[0].companies.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "company"
});
}.bind(this)) // changed here
data[1].centers.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "center"
});
}.bind(this)) //changed here
}
)
}
Upvotes: 0
Reputation: 253
You are not instantiating that service anywhere. If you want a singleton, you need to add it in the constructor()
as one of the parameters, and it gets injected there and retrieves the instance. You can then use this
to access it.
constuctor(_ds: DataServiceProvider)
Upvotes: 1