Ionic 4 Service构造函数从未调用-> httpClient http.get fail

时间:2019-03-20 20:32:43

标签: angular ionic-framework ionic4 angular-httpclient

我在这里迷路了,我不知道为什么会有这个错误:

它的离子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 {
}

some.page.ts

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

更新(2019-03-21 17:50(GMT)): 已经尝试过。

  • 从app.module.ts中删除HttpClient
  • 添加@Injectable({provedIn:'root'})
  • 从app.module.ts中删除HttpServiceService
  • 私人http:Http;从'@ angular / http'导入{Http}; (不建议使用)

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

中被调用

更新结束

0 个答案:

没有答案