angular - 从未调用过 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(格林威治标准时间)): 已经尝试过了。
- 从 app.module.ts 中删除 HttpClient
- 添加@Injectable({ providedIn: 'root' })
- 从 app.module.ts 中删除 HttpServiceService
- 私有http:http;从'@angular/http'导入{Http};(顺便说一句,已弃用)
查看整个代码:https ://github.com/digital-scouts/Frontend/tree/dev/src/app 我的 http-service 在 loading.page.ts:100 中被调用
更新结束
解决方案
推荐阅读
- java - Java "x += y" 和 "x = x+y" 产生不同的结果
- python-3.x - 使用 sqlite3 插入二进制数据
- azure - 身份验证不会重定向回我在 Xamarin.Forms 中的 Android 应用
- javascript - 如何将点击处理程序添加到已经使用 onClick 的第三方组件?
- java - 如何使用 Java 在现有 Json 文件上附加数据?
- swift - swift 在方法参数上使用语法
- android - 动态更新新闻应用程序的视图(viewpager)
- javascript - 返回带有 onclick cookie 值的 html 按钮
- ksh - 在 shell 中获取错误的数字
- ruby-on-rails - 如何使用数据库条目作为 ruby on rails 的元描述