为角度创建节点模块

问题描述 投票:0回答:1

我是第一次尝试创建节点模块包。

我写了一个使用HttpClient模块的服务,来自“@ angular / common / http”

我的服务代码如下所示:

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

@Injectable()
export class HttpClientProvider {
    baseUrl: string;

    constructor(private http: HttpClient) {

    }

    // Preform the request and return a promise to the caller;
    private doRequest(requestType:string,url: string, body:any, options:any): Promise<any> {
        return new Promise((resolve, reject) => {
            return this.http[requestType](url,body,options).subscribe(data => {
                resolve(data);
            }, error => {
                reject(error);
            });
        });
    }

    // Use this function for GET WS
    getRequest(url: string): Promise<any> {
        return this.doRequest('get', url,{},{});
    }

    // Use this function for POST WS
    postRequest(url: string, body: any): Promise<any> {
        return this.doRequest('post', url, body,{});
    }
}

然后我使用“npm install”将它安装到我的角度项目中。安装完成后,我将其添加到app.module文件中的提供程序。

问题是什么时候尝试在组件中使用它我收到消息“错误:没有HttpClient的提供程序!”

我试图将HttpClient添加到提供者列表中,但它没有改变任何东西......

我的组件构造函数看起来像这样

constructor(fb:FormBuilder, http: HttpClientProvider) {
    this.signInDetails = new SigninDetails();
    this.form = fb.group({
      'userName': ['', Validators.compose([Validators.required])],
      'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
    });

    this.userName = this.form.controls['userName'];
    this.password = this.form.controls['password'];
  }

我不明白我做错了什么......有什么建议吗?

我的AppModule看起来像这样

@NgModule({
  bootstrap: [App],
  declarations: [
    App
  ],
  imports: [ 
    BrowserModule,
    HttpClientModule,
    HttpModule,
    RouterModule,
    BrowserAnimationsModule,
    PagesModule,
    routing
  ],
  providers: [ 
    HttpClientProvider,
    APP_PROVIDERS
  ]
})
angular npm node-modules
1个回答
0
投票

HttpClient就像你的服务一样,所以它必须由某个模块“提供”。您应该在应用程序的某处导入HttpClientModule。最好是在app.modulecore.module(如果你有一个核心模块)。您不能只在模块中提供HttpClient,因为它还需要其他服务。幸运的是,HttpClientModule为您做到了。

app.module.ts

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpClientModule
  ],
  exports: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
© www.soinside.com 2019 - 2024. All rights reserved.