在Angular中,一个服务可以依赖于另一个服务。以下是一些最佳实践:
import { Injectable } from '@angular/core'; import { UserService } from './user.service';
@Injectable({ providedIn: 'root' }) export class AuthService {
constructor(private userService: UserService) {}
login(username: string, password: string) { this.userService.login(username, password); } }
import { Injectable } from '@angular/core'; import { UserService } from './user.service';
@Injectable({ providedIn: 'root' }) export class AuthService {
constructor(private userService: UserService) {}
login(username: string, password: string) { this.userService.login(username, password); } }
@Injectable({ providedIn: 'admin' }) export class UserService {
login(username: string, password: string) { // Admin login logic } }
在上面的例子中,UserService被注入到admin模块中,因此只有admin模块中的AuthService可以使用UserService。
import { Injectable } from '@angular/core';
export interface ILogger { log(message: string); }
@Injectable({ providedIn: 'root' }) export class LoggerService implements ILogger {
log(message: string) { console.log(message); } }
@Injectable({ providedIn: 'root' }) export class UserService {