Angular 7注入的服务在刷新后尝试调用方法时抛出TypeError



我有一个组件DevicePage,它在其构造函数中请求ServiceAdapter的实例,然后使用该ServiceAdapter来请求ngOnInit()中的信息。ServiceAdatper还请求Service的实例进行http调用,然后将响应转换为DevicePage所需的对象。我的简化代码是:

@Component({
selector: 'app-device',
templateUrl: './device.page.html',
styleUrls: ['./device.page.scss'],
})
export class DevicePage implements OnInit {
private device: Device;    // beacon used in the HTML template to display info
constructor(private activatedRoute: ActivatedRoute, private adapter: ServiceAdapter) {
}
ngOnInit() {
// Grab the beacon details
this.adapter
.getDevice(this.activatedRoute.snapshot.paramMap.get('id'))
.subscribe(device=> this.device = device);
}
}
@Injectable({
providedIn: 'root'
})
export class ServiceAdapter {
constructor(private service: Service) {
}
getDevice(id: string): Observable<Device> {
this.service.getDevice(id).pipe(
map(response => {
return this.extractDevice(response.data).shift();
})
)
}
private extractDevice(devices: Device[]) {
return devices.map(device => <Beacon> {
id: device.identifier,
name: device.shadow.name
});
}
}
@Injectable({
providedIn: 'root'
})
export class Service {
constructor(http: HttpClient) {
this.http = http;
}
getDevice(id): Observable<DevicesResponseV3> {
return this.http.get<DevicesResponseV3>(URL_DEVICES)
.pipe(catchError(err => this.handleError(err)));
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Error response from ${error.url} ` +
`Backend returned code ${error.status} ` +
`body was: ${error.message}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
}
}

当我第一次打开应用程序并导航到该页面时,一切都如预期。但是,当我刷新页面时,会出现以下错误:ERROR TypeError: "this.adapter.getDevice(...) is undefined"。服务本身并没有定义,我不确定发生了什么。

我的app.module.ts文件的内容:

@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule,
IonicStorageModule.forRoot(),
AngularFireModule.initializeApp(environment.firebase, 'herald-client-webapp'),
AngularFireAuthModule, // imports firebase/auth, only needed for auth features
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}

在运行ionic serve时,您是否通过保存一些代码来刷新页面?

如果是这样的话,不要担心当你发布应用程序时它会起作用,设置调试器并查看:

getDevice(this.activatedRoute.snapshot.paramMap.get('id'))

id可能为null。您还可以在输入页面时获取参数:

ionViewWillEnter() {
this.estimote
.getDevice(this.activatedRoute.snapshot.paramMap.get('id'))
.subscribe(device=> this.device = device);
}