![](/img/trans.png)
[英]What is the purpose of providedIn with the Injectable decorator when generating Services in Angular 6?
[英]Angular Service not acting as singleton when injected in components despite using @Injectable({providedIn: 'root' }) decorator
我有一個項目,其中包含兩個模塊(默認的 AppModule 和創建項目時由 angular cli 生成的路由模塊),我創建的兩個組件和我注入到每個組件的構造函數中的服務。 我希望有相同的服務實例(每次我注入服務時都是單例,因為它有 @Injectable({providedIn: 'root' }) 裝飾器)但每次導航時我都會得到一個全新的服務實例到我的每個組件。 這是我的代碼如下:
應用模塊.html
\<router-outlet\>\</router-outlet\>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { Test2Component } from './test2/test2.component';
@NgModule({
declarations: [
AppComponent,
TestComponent,
Test2Component
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TestComponent } from './test/test.component';
import { Test2Component } from './test2/test2.component';
const routes: Routes = [
{ path: 'test1', component: TestComponent },
{ path: 'test2', component: Test2Component }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
test.component.ts
import { Component} from '@angular/core';
import { TestService } from '../test.service';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent {
constructor(private _testService: TestService) { }
}
test2.component.ts
import { Component } from '@angular/core';
import { TestService } from '../test.service';
@Component({
selector: 'app-test2',
templateUrl: './test2.component.html',
styleUrls: ['./test2.component.css']
})
export class Test2Component {
constructor(private _testService: TestService) { }
}
測試服務.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestService {
private date = new Date();
constructor() {
console.log("Inside the service ", this.date);
}
}
像這樣在 app.module.ts 中的 providers 數組中提供您的測試服務。 創建單例。
提供者:[TestService]
從代碼的外觀來看,您的服務確實是 Singleton。
將此插入到 app.component.html,並嘗試鏈接:
<nav>
<ul>
<li><a routerLink="child-a">Child A</a></li>
<li><a routerLink="child-b">Child B</a></li>
</ul>
</nav>
我懷疑您嘗試通過在瀏覽器導航欄中寫入 url 來檢查這兩個組件,因此在您認為要重新路由時重新加載應用程序。 可能是這樣嗎?
我創建了路由和單服務使用的工作示例這里。
請參閱以下鏈接: https : //www.w3resource.com/angular/angular-singleton-service.php
您需要在 app.module.ts 中將您的服務注冊為提供者。
providers: [{provide: Service}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.