Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度6和#x27;无法读取未定义的';在服务中调用函数时_Angular_Typescript_Http Post_Angular Services_Angular Httpclient - Fatal编程技术网

Angular 角度6和#x27;无法读取未定义的';在服务中调用函数时

Angular 角度6和#x27;无法读取未定义的';在服务中调用函数时,angular,typescript,http-post,angular-services,angular-httpclient,Angular,Typescript,Http Post,Angular Services,Angular Httpclient,我正在尝试调用服务内部的函数,但我一直无法读取未定义的属性“authenticationService” 我已经在组件的构造函数中初始化了authenticationService 组成部分: export class RegisterComponent implements OnInit { error: string; isLinear = true; registerFormGroup: FormGroup; loading = false; form: FormGr

我正在尝试调用服务内部的函数,但我一直无法读取未定义的属性“authenticationService”

我已经在组件的构造函数中初始化了
authenticationService

组成部分:

 export class RegisterComponent implements OnInit {
  error: string;
  isLinear = true;
  registerFormGroup: FormGroup;
  loading = false;
  form: FormGroup;
  studentRegister: any;
  samePassword = false;
  hide = true;
  hide1 = true;
  matcher = new MyErrorStateMatcher();

constructor(
   private router: Router,
   private _formBuilder: FormBuilder,
   private http: HttpClient,
   private i18nService: I18nService,
   private authenticationService: AuthenticationService
) {
}

ngOnInit() {
    this.registerFormGroup = this._formBuilder.group({
    first_name: [null, Validators.compose([Validators.required,                 Validators.minLength(3), Validators.maxLength(20)])],
    last_name: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(20)])],
    email: [null, Validators.compose([Validators.required, Validators.email])],
    password: [null, Validators.compose([Validators.required])],
    tel: [null, Validators.compose([Validators.required])],
    confirmPassword: [null]
}, {
  validator: [this.checkPasswords, this.checkEmailUnique]
});
}

checkEmailUnique(group: FormGroup) {
 const mail = group.controls.email.value;
 const obj: any = {'email': mail, } ;
 this.authenticationService.checkEmailUnique(obj);
}

checkPasswords(group: FormGroup) { // here we have the 'passwords' group
 const pass = group.controls.password.value;
 const confirmPass = group.controls.confirmPassword.value;
 return pass === confirmPass ? null : {notSame: true};
}}

register() {
   console.log('the form is', this.registerFormGroup);
     // stop here if form is invalid
     if (this.registerFormGroup.invalid) {
      return;
     }
    this.loading = true;
    this.authenticationService.register(this.registerFormGroup.value)
     .pipe(finalize(() => {
        this.loading = false;
       }))
       .subscribe(credentials => {
        log.debug(`${credentials.email} successfully logged in`);
        this.router.navigate(['/'], {replaceUrl: true});
       }, error => {
        log.debug(`Login error: ${error}`);
        this.error = error;
       });
   }
服务:

@Injectable()
 export class AuthenticationService {
  private _credentials: Credentials | null;

  constructor(private http: HttpClient) {
    const savedCredentials = sessionStorage.getItem(credentialsKey) ||    localStorage.getItem(credentialsKey);
     if (savedCredentials) {
     this._credentials = JSON.parse(savedCredentials);
     }
     }

register(context: UserInfo): Observable<Credentials> {
    // Replace by proper authentication call
    let data = {
     email: context.email,
     token: '',
     user_type: ''
     };

    return this.http.post('/account/create_new/', JSON.stringify({
     first_name: context.first_name,
     last_name: context.last_name,
     email: context.email,
     password: context.password,
     tel: context.tel,
     user_type: 'S',
     student: {}
    }), httpOptions)
     .pipe(
       map((response: any) => {
        console.log(response.user_type);
        data.user_type = response.user_type;
        data.token = response.token;
        this.setCredentials(data, true);
         return data;
        })
      );
}

checkEmailUnique(obj: any) {
     return this.http.post('/check_email/', obj, httpOptions)
     .pipe(
      map((response: any) => {
      console.log(response);
      return response;
    })
  );}}
@Injectable()
导出类身份验证服务{
私有|凭证:凭证|空;
构造函数(专用http:HttpClient){
const savedCredentials=sessionStorage.getItem(credentialsKey)| | localStorage.getItem(credentialsKey);
如果(savedCredentials){
此._credentials=JSON.parse(savedCredentials);
}
}
寄存器(上下文:UserInfo):可观察{
//替换为正确的身份验证调用
让数据={
电子邮件:context.email,
令牌:“”,
用户类型:“”
};
返回此.http.post('/account/create_new/',JSON.stringify({
first\u name:context.first\u name,
last_name:context.last_name,
电子邮件:context.email,
密码:context.password,
电话:context.tel,
用户类型:“S”,
学生:{}
}),httpOptions)
.烟斗(
map((响应:任意)=>{
console.log(响应.用户类型);
data.user\u type=response.user\u type;
data.token=response.token;
此.setCredentials(数据,true);
返回数据;
})
);
}
checkEmailUnique(对象:任何){
返回此.http.post('/check_email/',obj,httpOptions)
.烟斗(
map((响应:任意)=>{
控制台日志(响应);
返回响应;
})
);}}
register()
中调用
authenticationService
可以正常工作。
checkEmailUnique
应该向后端发送POST请求,该后端检查电子邮件是否已经存在,并返回true或false。

由于将从另一个上下文调用验证程序,因此authenticationService在那里不可用。尝试使用箭头函数,以便保留此上下文:

checkEmailUnique=(组:FormGroup)=>{
const mail=group.controls.email.value;
const obj:any={'email':mail,};
this.authenticationService.checkEmailUnique(obj);
}
此外,由于authenticationService中的checkEmailUnique函数将返回Observable,因此您需要使用AsyncValidator