[英]Of components, shared services and children in angular2
我想在一個組件及其子組件之一之間創建共享服務(我有一個包含多個注釋的項目,並且想要更新注釋)
因此,在組件“ A”中,我將執行以下操作
import {SharedService} from "../services/my.shared.service";
...
@Component({
selector: 'foo',
templateUrl: './foo.html',
styleUrls: ['./foo.scss'],
providers: [SharedService]
})
...
constructor(private _sharedService:sharedService) { }
...
我在該組件中有一條路線
this._router.navigate(['./bar'],{relativeTo: this._route});
我的路線是這樣定義的
{
path: 'foo/:id',
component: FooComponent,
children: [
{
path: 'bar',
component: BarComponent
}
]
},
因此,“酒吧”組件
import { Component, OnInit } from '@angular/core';
import {SharedService} from "../services/my.shared.service";
@Component({
selector: 'bar',
templateUrl: './bar.html',
styleUrls: ['./bar.scss']
})
export class BarComponent implements OnInit {
constructor(private _sharedService:sharedService) { }
async ngOnInit() {
let item:any = await this._sharedService.getCurrentItem();
console.log("xxxx",item)
}
}
全部編譯。
但是,當我單擊導航到bar
的按鈕時,我得到了
錯誤錯誤:未捕獲(承諾):錯誤:找不到要加載“ BarComponent”的主要出口
現在,我知道這是因為我的Foo
模板沒有<router-outlet>
。 這是有原因的-我希望bar模板在可視化時替換foo模板。
我確實嘗試過這樣設置路線
{
path: 'foo/:id',
component: FooComponent
},
{
path: 'foo/:id/bar',
component: BarComponent
}
但是我得到了錯誤
錯誤錯誤:未捕獲(承諾):錯誤:沒有SharedService的提供程序!
所以,我該怎么辦
A)用子欄模板替換我的foo模板B)修復提供程序錯誤?
ng2 / 4的新功能,路由器和插座,所以我可能缺少一些基本知識
更新#1我曾考慮過將<router-outlet>
放入foo模板,並用“ * ngIf = inParentMode”包裝父模板,但這似乎非常“ hacky”
我認為你必須讓你的心-你提到有FooComponent
由一個替代BarComponent
通過路由。 這意味着FooComponent
和BarComponen
t是彼此的兄弟,並且您的路由應該類似於您的第二個路由示例:
{
path: 'foo/:id',
component: FooComponent
},
{
path: 'foo/:id/bar',
component: BarComponent
}
但是,如果FooComponent
和BarComponent
是同級,則不能通過在一個中聲明一個提供程序來在它們之間共享服務-根據定義,當您在組件中聲明一個提供程序時,就是說您想要該提供程序的唯一實例。該部分及其所有子項 。 FooComponent
是同級BarComponent
,而不是它的父(再次,根據你描述如何您的使用場景)。
在這種情況下,您有兩個選擇:
在實際上是FooComponent和BarComponent父級的組件中聲明共享服務提供者(從您的路由代碼中,可能是AppComponent),或者
在NgModule級別聲明您的共享服務提供者-通常,這是在大多數情況下的更好方法(除非您明確利用了“每個組件的唯一實例”功能) 。
因此,從FooComponent
刪除服務的提供程序聲明,並將其添加到聲明這些組件的NgModule中(可能是AppModule
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.