繁体   English   中英

Angular2将服务注入另一个服务

[英]Angular2 Injecting Service into another Service

我找不到我的错误。

app.module.ts
    ...
    providers: [ValidateService,AuthService]
    ...

我在register.component.ts中执行以下操作:

import {AuthService} from '../../services/auth.service';
...
constructor( private _validateService: ValidateService,
               private _fms: FlashMessagesService,
               private _authService: AuthService,
               private _router: Router
               ) { }
...
ngOnInit() { 
      this._authService.uniqueUser({username:'zomh'}).subscribe(data => {
      console.log("data.success: "+data.success);       
      if(!data.success) {   // Username already exists       
        console.log('exists');
      }
      else {
         console.log('does not exist');
      }
      });
  }

按预期工作的用户已经在数据库中,因此我得到一个用户存在于控制台中。

我在validate.service.ts中几乎做同样的事情(将其分解为这一点):

import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';



@Injectable()
export class ValidateService {

  constructor( public _authService: AuthService) { }

  validateRegister(user) {
    if(user.name == undefined || user.email == undefined || user.username == undefined || user.password == undefined)
      return false;
    else
      return true;
  }

  validateEmailPattern(c: FormControl) {
     const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

     if (re.test(c.value))
      return null;
     else
      return {invalidPattern:true};

  }
  validateUsernamePattern(c: FormControl) {
    const re = /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/

    if (re.test(c.value))
      return null;
    else
      return {invalidPattern:true};

  }
  validateUsernameIsUnique (c: FormControl) {

    let ret:any;
    if (c.value.length >= 3)
    {
      console.log(c.value);
      this._authService.uniqueUser({username:'zomh'}).subscribe(data => {

      if(!data.success) {   // Username already exists       
        console.log('call from service: exists');
      }
      else {
         console.log('call from service: does not exist');
      }
      });

    }

    return {usernameIsTaken:true};
  }


}

但是在这里,我得到了Cannot read property _authService of undefined异常 在此处输入图片说明

对我来说,该服务似乎未正确注入。 但是我找不到我的错误。

更新1:所以我确实将auth Service调用复制到了构造函数中并工作。 因此,必须要有一些。 相关错误(?)我无法从构造函数之外的任何其他方法获取this._authService的值?

@Injectable()
export class ValidateService {

  constructor( private _authService: AuthService ) { 

        this._authService.uniqueUser({ username: 'zomh' }).subscribe(data => {

        if (!data.success) {   // Username already exists       
          console.log('call from service: exists');
        }
        else {
          console.log('call from service: does not exist');
        }
      });
  }

我不认为您可以在@Injectableexport class ValidateService {

尝试没有那条线。

阅读文章后,我将方法重写为实例方法:

 validateUsernameIsUnique = (c: FormControl) => {

    let ret: any;
    if (c.value.length >= 3) {      
      this._authService.uniqueUser({ username: c.value }).subscribe(data => {

        if (!data.success) {   // Username already exists       
          console.log('call from service: exists');
        }
        else {
          console.log('call from service: does not exist');
        }
      });

    }
...

它解决了问题。 我仍然不确定为什么必须这样做,请随时添加知识

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM