網(wǎng)站icp備案認(rèn)證怎么做世界足球排名最新
在Angular中有很多方式可以將服務(wù)類注冊(cè)到注入器中:
@Injectable 元數(shù)據(jù)中的providedIn屬性
@NgModule 元數(shù)據(jù)中的 providers屬性
@Component 元數(shù)據(jù)中的 providers屬性
創(chuàng)建一個(gè)文件名叫名 hero.service.ts叫 hero 的服務(wù)
?hero.service.ts
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root',
})
export class HeroService {constructor() { }// 新增加setName方法setName(name:string):string{return `姓名:${name}`;}}
1.@Injectable 元數(shù)據(jù)中的providedIn屬性
providedIn: 'root' 告訴 Angular在根注入器中注冊(cè)這個(gè)服務(wù),這也是使用CLI生成服務(wù)時(shí)默認(rèn)的方式.
這種方式注冊(cè),不需要再@NgModule裝飾器中寫providers,而且在代碼編譯打包時(shí),可以執(zhí)行搖樹優(yōu)化,會(huì)移除所有沒在應(yīng)用中使用過的服務(wù)。推薦使用此種方式注冊(cè)服務(wù)
使用providedIn的話,后面直接在項(xiàng)目中使用了。
使用:heroes.component.ts
import { Component, OnInit } from '@angular/core';
import { HeroService } from '../hero.service'@Component({selector: 'app-heroes',templateUrl: './heroes.component.html',styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {constructor(private heroService:HeroService) { }ngOnInit() {this.heroService.setName('張三');}
}
2.@NgModule 元數(shù)據(jù)中的 providers屬性
改寫 hero.service.ts里面的@Injectable,如下
import { Injectable } from '@angular/core';@Injectable() // 刪掉了 {providedIn: 'root'}
export class HeroService {...}
?xx.module.ts , 例如app.module.ts
...@NgModule({providers: [HeroService,// { provide: HeroService, useValue: HeroService }],
})...
然后就可以在使用拉,使用方法,同1 heroes.component.ts文件
3.@Component 元數(shù)據(jù)中的 providers屬性
?hero.service.ts里面的@Injectable,刪掉 {providedIn: 'root'},同2 hero.service.ts文件
改寫heroes.component.ts
import { Component, OnInit } from '@angular/core';
import { HeroService } from '../hero.service'@Component({selector: 'app-heroes',templateUrl: './heroes.component.html',styleUrls: ['./heroes.component.css'],providers: [HeroService] // 新增 providers: [HeroService]
})
export class HeroesComponent implements OnInit {constructor(private heroService:HeroService) { }ngOnInit() {this.heroService.setName('張三');}
}
?
三種用法總結(jié):
@Injectable 元數(shù)據(jù)中的providedIn屬性 ?
//service.ts
@Injectable({providedIn:'root'})//component.ts
constructor(private heroService:HeroService) { }
@NgModule 元數(shù)據(jù)中的 providers屬性
// service.ts
@Injectable()?//module.ts
@NgModule({providers: [HeroService ]
})
@Component 元數(shù)據(jù)中的 providers屬性
// service.ts
@Injectable()?// component.ts
@Component({...selector: 'app-heroes',providers: [ HeroService ]
})
原文鏈接:https://blog.csdn.net/sllailcp/article/details/102548144