将Angular service1导入service2

时间:2018-07-31 16:21:00

标签: angular typescript firebase dependency-injection

这是Angular 6和Firestore应用程序。我正在尝试将service1导入service2并收到以下错误。

compiler.js Uncaught Error: Can't resolve all parameters for Service1

我已经阅读了这篇Medium article和这篇stackoverflow帖子,但都没有提供见识。

这是我的代码。

首先,我在app.module.ts

中导入和列出这两种服务作为提供者
#### app.module.ts ####

import { AuthenticationService } from './authentication.service';
import { UserService } from './user.service';

@NgModule({
  ...
  providers: [
    AuthenticationService,
    UserService
  ]
  ...
})

服务1 AuthenticationService是这个

#### authentication.service.ts ####

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { User } from './models/user.model';
import { UserService } from './user.service';

@Injectable({
  providedIn: 'root'
})

export class AuthenticationService {
  user: Observable<firebase.User>;

  constructor(private afAuth: AngularFireAuth,
              private router: Router,
              public userService: UserService ) {
                this.user = afAuth.authState;
              }
}

将service1 AuthenticationService添加到service2 UserService中的构造函数时,出现上面列出的编译器错误。

#### user.service.ts ####

import { Injectable } from '@angular/core';
import * as firebase from 'firebase/app';
import {
  AngularFirestore,
  AngularFirestoreDocument,
  AngularFirestoreCollection
} from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { User } from './models/user.model';
import { AuthenticationService } from './authentication.service';

@Injectable({
  providedIn: 'root',
})

export class UserService {
  usersCollection: AngularFirestoreCollection<User>;
  users: Observable<User[]>;
  username;

  constructor(private afs: AngularFirestore, 
              private authserv: AuthenticationService) {
    this.usersCollection = this.afs.collection('users');
    this.users = this.usersCollection.valueChanges();

    this.authserv.user.subscribe(user => {
      if (user != null) {
        console.log('Id is: ' + user.uid);
      }
    });
  }
}

我在某处缺少一些代码吗?谢谢。

1 个答案:

答案 0 :(得分:0)

如上面的评论所述,不可能两者都

  • 使用service1作为依赖项来构建service2
  • 并以service2作为依赖项构造service1

您可以选择其中之一,但不能同时选择两者。