簡體   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