首页 > 解决方案 > 从未调用过 Ionic 4 服务构造函数-> httpClient http.get 失败

问题描述

我在这里迷路了,我不知道为什么会出现此错误:

它的离子 4

我为我所有的其余 api 通信提供服务。http在服务中未定义,所以.post失败。那么为什么我的服务构造函数从未被调用呢?

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'post' 
of undefined
TypeError: Cannot read property 'post' of undefined
at Object.<anonymous> (http-service.service.ts:27)
...

http-service.service.ts:

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class HttpServiceService {
constructor(
    private httpClient: HttpClient
) {
    console.log('service'); // not called
}

async poster() {
    console.log(this.httpClient); // undefined
     this.httpClient
        .post(this.backend_url, {/*params*/})
        .subscribe(res => {});

}
}

app.module.ts

...
import {HttpClient} from '@angular/common/http';
import {HttpClientModule} from '@angular/common/http';

import {HttpServiceService} from './http-service.service';

@NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
        BrowserModule,
        HttpClientModule,
        IonicModule.forRoot(),
        IonicStorageModule.forRoot(),
        AppRoutingModule,
    ],
    providers: [
        StatusBar,
        SplashScreen,
        HttpClient,
        HttpServiceService,
        {provide: RouteReuseStrategy, useClass: IonicRouteStrategy}
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

一些.page.ts

import {HttpServiceService} from '../http-service.service';
...
constructor(private http: HttpServiceService) {...}
....
this.http.poster()

更新(2019-03-21 17:50(格林威治标准时间)): 已经尝试过了。

查看整个代码:https ://github.com/digital-scouts/Frontend/tree/dev/src/app 我的 http-service 在 loading.page.ts:100 中被调用

更新结束

标签: angularionic-frameworkionic4angular-httpclient

解决方案


推荐阅读