Хорошо, поскольку ваш код сложен для понимания, я хотел бы поделиться с вами информацией о том, как бы я его организовал, обратите внимание, что я еще не знаю, какой модуль http вы используете, и есть разница между современным (более 4.3 угловым) модулем. и старый. Я написал ниже, имея в виду современный:
в вашем rest-service.ts (провайдер, которого вы будете импортировать в ваши компоненты):
// do all of your specific imports here:
import { Injectable } from '@angular/core';
import { Storage } from "@ionic/storage";
@Injectable()
export class RestService {
// cache token here to use in your restful calls:
userToken: string;
constructor (
) {
// obtain token once during service instantiation, service providers don't have lifecycle hooks but it is OK to do init values inside the constructor:
this.getToken();
}
// this will get called once with constructor execution:
getToken() {
this.storage.get('Token').then((token) => {
this.userToken = token;
});
};
getCars() {
// depending on your HTTP module used in Ionic (Angular < 4.3 or > 4.3):
// only set Authorization property in header once:
const headers = new HttpHeaders().set('Authorization', 'Bearer ' + this.userToken);
// so http requests will return observables (if Angular 4.3 HttpClient module is used), you will subscribe to it in your components:
return this.http.get(url, { headers: headers})
}
}
Теперь в ваших cars.ts:
// do your proper imports here:
import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';
import { RestService } from '../../app/providers/rest-service';
import { LoadingController } from 'ionic-angular';
import { AlertController} from "ionic-angular";
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
// component var that will get assigned values:
cars: Array<string> = [];
constructor(public restService: RestService, public loadingController: LoadingController) {
}
// this life cycle hook is only called once when component enters memory, feel free to use other hooks as needed for your app, but key thing is that you call method in provider and subscribe/unsubscribe in components.
ionViewDidLoad() {
// here on component load into memory you can call the method:
this.restService.getCars().subscribe((carsData) => {
this.cars = carsData;
}, (error)=>{
console.log(error);
});
}
}
Ваш шаблон может быть таким:
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Welcome to Cars Page!</h2>
<ion-list>
<ion-item *ngFor="let car of cars">
<ion-label>{{ car.title }}</ion-label>
</ion-item>
</ion-list>
</ion-content>