第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將數(shù)據(jù)傳遞給Angular路由組件?

如何將數(shù)據(jù)傳遞給Angular路由組件?

慕斯王 2019-09-04 06:04:04
如何將數(shù)據(jù)傳遞給Angular路由組件?在我的一個Angular 2路線的模板(FirstComponent)中,我有一個按鈕first.component.html<div class="button" click="routeWithData()">Pass data and route</div>我的目標是實現(xiàn):按鈕單擊 - >路由到另一個組件,同時保留數(shù)據(jù),而不使用其他組件作為指令。這就是我試過的......第一種方法在同一視圖中,我存儲基于用戶交互收集相同的數(shù)據(jù)。first.component.tsexport class FirstComponent {      constructor(private _router: Router) { }      property1: number;      property2: string;      property3: TypeXY; // this a class, not a primitive type     // here some class methods set the properties above     // DOM events     routeWithData(){          // here route     }}一般情況下我路由SecondComponent通過 this._router.navigate(['SecondComponent']);最終傳遞數(shù)據(jù) this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);而帶參數(shù)的鏈接的定義是@RouteConfig([       // ...       { path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent} )]這種方法的問題是我猜我無法傳遞復雜數(shù)據(jù)(例如像property3這樣的對象)in-url;第二種方法另一種方法是在FirstComponent中包含SecondComponent作為指令。  <SecondComponent [p3]="property3"></SecondComponent>但是我想要路由到該組件,而不是包含它!第三種方法我在這里看到的最可行的解決方案是使用服務(例如FirstComponentService)將數(shù)據(jù)(_firstComponentService.storeData())存儲在FirstComponent中的routeWithData()上在SecondComponent中的ngOnInit()中檢索數(shù)據(jù)(_firstComponentService.retrieveData())雖然這種方法似乎完全可行,但我想知道這是否是實現(xiàn)目標的最簡單/最優(yōu)雅的方式。一般來說,我想知道我是否缺少其他可能的方法來在組件之間傳遞數(shù)據(jù),特別是在代碼量較少的情況下
查看完整描述

3 回答

?
慕容3067478

TA貢獻1773條經(jīng)驗 獲得超3個贊

我想因為我們在角度2中沒有$ rootScope類似于角度1.x. 我們可以使用angular 2共享服務/類,而在ngOnDestroy中將數(shù)據(jù)傳遞給服務,并在路由后從ngOnInit函數(shù)中的服務獲取數(shù)據(jù):

這里我使用DataService來共享英雄對象:

import { Hero } from './hero';export class DataService {
  public hero: Hero;}

從第一頁組件傳遞對象:

 ngOnDestroy() {
    this.dataService.hero = this.hero; 
 }

從第二頁組件獲取對象:

 ngOnInit() {
    this.hero = this.dataService.hero; 
 }

這是一個例子:plunker



查看完整回答
反對 回復 2019-09-05
  • 3 回答
  • 0 關(guān)注
  • 572 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號