[英]how to pass data from one component to another component in angular 2?
我在角度2應用程序(ComponentOne和ComponentTwo)中有兩個組件。 ComponentOne需要用戶詳細信息和用戶首選項來執行某些操作,因此我在初始化ComponentOne時從后端服務獲取這些詳細信息。
@Component({
selector: 'componentOne',
template: 'componentOneTemplate',
styles: ['componentOneStyles'],
providers: []
})
export class ComponentOneComponenet implements OnInit {
//getting user details
getUserDetails();
//getting user preferences
getUserPreferences();
}
我用戶路由器從ComponentOne路由到ComponentTwo。
<router-outlet></router-outlet>
現在我再次想要ComponentTwo中的userDetails和userPreferences。 有沒有辦法在這兩個組件之間共享數據而不是再次調用后端服務?
您可以像其他人建議的那樣簡單地在服務中緩存數據。
根據用例可能相關的另一個解決方案是解析父狀態中的數據並從組件中的ActivatedRoute
獲取數據。 現在,當您在組件1和組件2之間導航時,將不會再次觸發解析器。 當父狀態再次激活時,它們將再次被觸發,這可能或可能不是您想要/需要的。
path: '',
resolve: [
userDetails: UserDetailsResolver,
userPreferences: UserPreferencesResolver
],
children: [{
path: 'one',
component: ComponentOne,
},{
path: 'two',
component: ComponentTwo,
}]
是的,最好的方法和最專業的方法是使用全球商店解決方案,如ngrx。
ngrx是行業標准,用於存儲應用程序的全局數據。
它使緩存數據變得非常容易。 我推薦Udemy的教程,但它們不是免費的。
或者,如果您只是想做一個快速的牛仔工作,那么使用服務並在服務中緩存HTTP響應,如下所示:
private res: any
public getMyData() {
return (this.res) ? of(this.res) : this.http.get('/api/some/path')
.pipe(res => {
this.res=res
})
}
並按正常方式訂閱調用代碼:
this.myService.getMyData().subscribe(res => {
console.log('res', res)
})
您可以調整getMyData()
並將布爾值傳遞給它,布爾值將指示緩存的響應是否足夠或是否再次發出HTTP請求。 但是,我沒有添加這個邏輯,因為我想讓事情變得簡單。
PS您需要在根模塊中提供服務,或者甚至更好地注入服務:
@Injectable({providedIn: 'root'})
我相信這種語法需要Angular 6。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.