我遇到数据服务问题,我认为每个人都遇到过这个问题! 我想要实现的是创建一个数据服务,在数据到达时更新视图! 换句话说我在第一页然后我从源加载数据列出它,然后我点击“添加新数据”按钮添加新项目并在我回去时发布到服务器,视图确实不要收回这个效果,我必须努力列出新项目
export class WorkoutPage implements OnInit{
workouts:WorkoutModel[];
ngOnInit(): void {
this.workoutservice.doRefersh();
}
constructor(private workoutservice:WorkoutService,
public navCtrl: NavController, public navParams: NavParams) {
this.workoutservice.workoutsList
.subscribe(worklist => {
console.log("GET WORKOUTS");
this.workouts = worklist;
});
}
ionViewDidLoad() {
}
workoutSelected(evt,w) {
this.navCtrl.push(WorkoutDetailPage, {
workout:w
})
}
}
数据服务
@Injectable()
export class WorkoutService{
workoutsList:BehaviorSubject<WorkoutModel[]> = new BehaviorSubject<WorkoutModel[]>([]);
apiKey:string;
apiUrl:string;
constructor(private _http:Http) {
console.log("Service connected");
this.apiKey="**************************";
this.apiUrl="*****;
}
doRefersh() {
console.log("doRefersh");
this._http.get(this.apiUrl+this.apiKey)
.subscribe(res => {
console.log("qs=>"+res.json());
this.workoutsList.next(<WorkoutModel[]>res.json());
});
}
addWorkout(workout) {
let mheaders = new Headers();
mheaders.append('Content-type','application/json');
let options: RequestOptionsArgs =
{
headers : mheaders
};
return this._http.post(this.apiUrl+this.apiKey,
JSON.stringify(workout),options).map( res => res.json());
}
}
离子标签页
export class TabsPage {
tabListWorkouts = WorkoutPage;
tabAddWorkout = AddWorkoutPage;
tabAbout = AboutPage;
constructor() {
}
}
<ion-tabs>
<ion-tab [root]="tabListWorkouts" tabTitle="Workouts" tabIcon="pulse"></ion-tab>
<ion-tab [root]="tabAddWorkout" tabTitle="Add Workout" tabIcon="add"></ion-tab>
<ion-tab [root]="tabAbout" tabTitle="Contact" tabIcon="contacts"></ion-tab>
</ion-tabs>