面试题答案
一键面试TypeScript装饰器在Angular框架中创建服务的方式
在Angular中,TypeScript装饰器通过@Injectable()
装饰器来将一个类标记为可注入的服务。当一个类被@Injectable()
装饰后,Angular的依赖注入系统就能够识别它,并可以将其注入到其他组件、服务或模块中。依赖注入使得代码的可测试性和可维护性大大提高,同时也实现了代码的解耦。
常用装饰器及其使用场景 - @Injectable()
使用场景:当你创建一个需要在应用的多个部分共享数据或功能的服务类时,就会用到@Injectable()
装饰器。例如,创建一个用于处理用户认证逻辑的服务,该服务可能包含登录、注销、获取用户信息等方法,并且需要在多个组件中使用。
示例代码:
import { Injectable } from '@angular/core';
// 使用 @Injectable() 装饰器将类标记为可注入的服务
@Injectable({
providedIn: 'root'
})
export class AuthService {
private isLoggedIn = false;
login() {
// 模拟登录逻辑
this.isLoggedIn = true;
}
logout() {
// 模拟注销逻辑
this.isLoggedIn = false;
}
isAuthenticated() {
return this.isLoggedIn;
}
}
在上述代码中,AuthService
类被@Injectable()
装饰,providedIn: 'root'
表示该服务在应用的根模块中提供,意味着整个应用都可以使用这个服务。然后在组件中就可以通过依赖注入的方式使用该服务:
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
constructor(private authService: AuthService) {}
onLogin() {
this.authService.login();
}
onLogout() {
this.authService.logout();
}
}
在LoginComponent
组件的构造函数中注入了AuthService
,从而可以调用其提供的方法来处理登录和注销逻辑。