简体   繁体   English

Angular2将服务注入另一个服务

[英]Angular2 Injecting Service into another Service

I can't find my error. 我找不到我的错误。

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

I do the following in my register.component.ts: 我在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');
      }
      });
  }

Works as expected the user is already in the database therefore I get the a user exists in the console. 按预期工作的用户已经在数据库中,因此我得到一个用户存在于控制台中。

I do pretty pretty much the very same thing (I broke it down to this point) in my validate.service.ts: 我在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};
  }


}

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

For me it looks like the service did not inject correctly. 对我来说,该服务似乎未正确注入。 But I can't find my error. 但是我找不到我的错误。

Update 1: So i did copy the auth Service call into the Constructor and its working. 更新1:所以我确实将auth Service调用复制到了构造函数中并工作。 Therefore it has to be some this. 因此,必须要有一些。 related error (?) i can't get the value of this._authService from any other method outside of the constructor ? 相关错误(?)我无法从构造函数之外的任何其他方法获取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');
        }
      });
  }

I dont think you can have a new line between @Injectable and export class ValidateService { 我不认为您可以在@Injectableexport class ValidateService {

Try it without that line. 尝试没有那条线。

After reading an article I rewrote my method into an instance method: 阅读文章后,我将方法重写为实例方法:

 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');
        }
      });

    }
...

It fixed the problem. 它解决了问题。 I am still not sure why this had to be done though, feel free to add knowledge 我仍然不确定为什么必须这样做,请随时添加知识

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

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