我正在调用Web API服务,而调试时我可以获取值。 但是在尝试赋值时,对象处于未定义状态。
this.selectedEvent = x;
this.selectedEvent 处于未定义状态。
在服务文件中,有以下方法按照id
返回事件getEvent(id: String){
return this.http.get(environment.baseApiURL + '/api/event/getevent/'+id)
.map(data => data.json() as Event);
}
这就是我调用服务的地方 event.component.ts
import { Component, OnInit } from '@angular/core';
import { EventService } from "../../event/shared/event.service";
import { Event } from "../shared/event.model";
import { Router, ActivatedRoute, Params } from '@angular/router';
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'
@Component({
selector: 'event-detail',
templateUrl: './event-detail.component.html',
styleUrls: ['./event-detail.component.css'],
providers: [EventService]
})
export class EventDetailComponent implements OnInit {
selectedEvent : Event;
loading: boolean = false;
constructor(public eventService: EventService, private route: ActivatedRoute){
this.selectedEvent = new Event();
}
ngOnInit() {
this.loading = true;
this.route.params.subscribe(params => {
this.eventService.getEvent(params['id']).subscribe(x=>{
this.selectedEvent = x;
this.loading = false;
});
});
}
}
答案 0 :(得分:-2)
这是Angular开发人员面临的一个非常普遍的问题。
ngOnInit() {
this.loading = true;
this.route.params.subscribe(params => {
this.eventService.getEvent(params['id']).subscribe(x=>{
this.selectedEvent = x;
this.loading = false;
});
});
}
此处this.selectedEvent = x;
写在subscribe()中,这意味着它只是范围在此函数内。
你可以做什么来获得this.selectedEvent
的值,你可以在subscribe()中调用一个函数并传递x。
这是一个例子:
ngOnInit() {
this.loading = true;
this.route.params.subscribe(params => {
this.eventService.getEvent(params['id']).subscribe(x=>{
this.getSelectedEvent(x);
this.loading = false;
});
});
}
getSelectedEvent(x){
this.selectedEvent = x;
}