【问题标题】:Creating a node modules for angular为角度创建节点模块
【发布时间】:2018-03-06 18:04:18
【问题描述】:

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

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

我的服务代码如下所示:

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”将它安装到我的 Angular 项目中。 安装完成后,我将它添加到我的 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】:

    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 {}
    

    【讨论】:

    • 我已经编辑了我的问题.. 我为我的 AppModules 添加了代码,但仍然没有运气:(
    • 从导入数组中删除 HttpModule。它已被弃用,可能会与 HttpClientModule 产生冲突
    • 试试看,没用..你认为为我的服务创建一个模块会有所作为吗?
    • 看看这个 stackblitz stackblitz.com/edit/angular-1w9ae7?file=app/app.module.ts 它工作得很好。您的项目一定有其他问题
    猜你喜欢
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2020-10-02
    • 1970-01-01
    • 2019-06-22
    • 2018-03-24
    相关资源
    最近更新 更多