[Angular 14] Inject() function

Before v14, we do DI like this:

@Component({
    name: 'app-root',
    template: `<h1>Hello!</h1>`
})
export class AppComponent {
    constructor(private http: HttpClient) {
    }
}

 

In V14, we can do:

@Component({
    name: 'app-root',
    template: `<h1>Hello!</h1>`
})
export class AppComponent {
    http = inject(HttpClient);
    auth = inject(AuthService);
    
    ngOnInit() {
        console.log(this.http);
    }
}

 

You can aslo use InjectionToken:

export cibst AUTH = new InjectionToken('AUTH', {
    providedIn: 'root',
    factory() {
        return inject(AuthService)
    }
})

@Component({
    name: 'app-root',
    template: `<h1>Hello!</h1>`
})
export class AppComponent {
    auth = inject(AUTH);
    
    ngOnInit() {
        console.log(this.auth);
    }
}

 

Use Factory in Providers:

@Injectable()
export class AuthService {
    constructor(http: HttpClient) {}
}

@NgModule({
    ...
    providers: [
        provide: AuthService,
        useFactory: () => {
            return new AuthService(inject(HttpClient))
        }
    ]
})

 

Other usecase:

//  Before 
export class AppComponent {
    constructor(private router: Router) {
        this.router.events.pipe(
            filter(e => e instanceof NavigationEnd)
        ).subscribe()
    }
}

// NOW
export function getRouterEvent() {
    return inject(Router).events
        .pipe(
            filter(e => e instanceof NavigationEnd)
        )
}

@Component()
export class AppComponent {
    routerEvents = getRouterEvent();
    constructor() {
        this.routerEvents.subscribe(console.log)
    }
}

 

posted @   Zhentiw  阅读(53)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-06-20 [ML L2 - N19] Naive Bayes GaussianNB
2019-06-20 [Cypress] Reuse Data with Cypress Fixtures
2017-06-20 [Preact] Integrate react-router with Preact
2017-06-20 [Angular] Change component default template (ng-content, ng-template, ngTemplateOutlet, TemplateRef)
2017-06-20 [Angular] Angular Advanced Features - ng-template , ng-container, ngTemplateOutlet
2013-06-20 【大型网站架构 原理】1. 负载均衡和冗余技术
点击右上角即可分享
微信分享提示