Browse Source

string Token

使用字串作為Inject token
master
HarveyMac 2 years ago
parent
commit
1d27146504
  1. 5
      src/app/app.component.html
  2. 6
      src/app/app.component.ts
  3. 4
      src/app/app.module.ts
  4. 0
      src/app/custom/custom.component.css
  5. 2
      src/app/custom/custom.component.html
  6. 20
      src/app/custom/custom.component.ts
  7. 11
      src/app/message.service.ts

5
src/app/app.component.html

@ -1,4 +1 @@
<hr>
<app-custom></app-custom>
<h3>AppComponent</h3>
<span>{{ messageService.message }}</span>
Loading 圖示位置:{{ loadingPath }}

6
src/app/app.component.ts

@ -1,6 +1,4 @@
import { Component } from '@angular/core';
import { MessageService } from './message.service';
import { Component, Inject } from '@angular/core';
@Component({
selector: 'my-app',
@ -8,5 +6,5 @@ import { MessageService } from './message.service';
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(public messageService: MessageService) {}
constructor(@Inject('LoadingPath') public loadingPath: string) {}
}

4
src/app/app.module.ts

@ -3,11 +3,11 @@ import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { CustomComponent } from './custom/custom.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, CustomComponent ],
declarations: [ AppComponent ],
providers: [{ provide: 'LoadingPath', useValue: 'assets/loading.gif'}],
bootstrap: [ AppComponent ]
})
export class AppModule { }

0
src/app/custom/custom.component.css

2
src/app/custom/custom.component.html

@ -1,2 +0,0 @@
<h3>CustomComponent</h3>
<span>{{ messageService.message }}</span>

20
src/app/custom/custom.component.ts

@ -1,20 +0,0 @@
import { Component, OnInit } from '@angular/core';
import { MessageService } from '../message.service';
@Component({
selector: 'app-custom',
templateUrl: './custom.component.html',
styleUrls: ['./custom.component.css'],
providers: [
{
provide: MessageService,
useValue: { message: '這是已經被替換掉的訊息' },
},
],
})
export class CustomComponent implements OnInit {
constructor(public messageService: MessageService) {}
ngOnInit() {}
}

11
src/app/message.service.ts

@ -1,11 +0,0 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MessageService {
message = '這是 MessageService 內的訊息'
constructor() { }
}
Loading…
Cancel
Save