Created
August 31, 2021 09:13
-
-
Save eneajaho/28c4ef1d75bf1d8733cec23e54068c0a to your computer and use it in GitHub Desktop.
Provide function with InjectionToken in Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Component, | |
Inject, | |
inject, | |
Injectable, | |
InjectionToken, | |
NgModule | |
} from '@angular/core'; | |
import { BrowserModule } from '@angular/platform-browser'; | |
@Injectable({ providedIn: 'root' }) | |
export class LoggerService { | |
success(message: string): void { | |
console.log('Success >>>> ', message); | |
} | |
} | |
// export const loggerFn = (message: string): void => console.log(message); | |
export type SuccessLogger = (message: string) => void; | |
export const Logger = new InjectionToken<SuccessLogger>( | |
'Logger Success function', | |
{ | |
factory: () => inject(LoggerService).success | |
// factory: () => loggerFn | |
} | |
); | |
@Component({ | |
selector: 'my-app', | |
template: ` | |
<button (click)="log('hahahaha')"> | |
Log to console | |
</button> | |
` | |
}) | |
export class AppComponent { | |
constructor(@Inject(Logger) public log: SuccessLogger) {} | |
} | |
@NgModule({ | |
imports: [BrowserModule], | |
declarations: [AppComponent], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule {} |
Author
eneajaho
commented
Sep 27, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment