无法读取angular7中未定义的属性“ post”

时间:2019-06-13 06:45:12

标签: javascript angular typescript angular7

我需要在angular 7中创建一个自定义验证。

编写此代码:

CheckUserNameExisit(control: AbstractControl): { [key: string]: any } {
 console.log('in functions')
 return new Promise(resolve => {
  let httpClient: HttpClient;
  var userService = new UserService(httpClient);
  let usernameExist: Usernameexist;
  usernameExist = userService.InitialUserNameExist();
  usernameExist.UserName = control.value;
  console.log(usernameExist.UserName)
  userService.checkUsername(usernameExist)
    .subscribe(data => {
      if (data.success == false) {
        console.log(data.success)
        resolve({ 'usernameExists': false });
      } else {
        console.log(true)
        resolve(null);
      }
    });
});
}

这是UserSerivce

checkUsername(item: Usernameexist): Observable<GenericModel<Usermodel>> {
  console.log('go')
  return this.httpClient.post<GenericModel<Usermodel>>('https://localhost:44372/api/v1/User/FindbyName/', item);
}

但是当我需要使用此验证时,它会向我显示此错误:

  

ERROR错误:未捕获(承诺):TypeError:无法读取未定义的属性“ post”   TypeError:无法读取未定义的属性“ post”       在UserService.push ../ src / app / services / user.service.ts.UserService.checkUsername

是什么问题?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

userservice 中,注入Httpclient

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

constructor(private http: HttpClient) { }

答案 1 :(得分:0)

您似乎尚未添加HTTPClientModuleAs Angular documentation says:

app.module.ts:

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

和yourservice.ts:

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

@Injectable()
export class YourService {
  constructor(private http: HttpClient) { }
}