0

我是新角度2;我使用typescript來編寫組件,我有一個「產品」對象,當登陸到網站時,用戶看到所有產品的列表(來自RESTful端點的JSON數據)。如果該用戶點擊列表中的某個產品,則會將其帶到一個「編輯」頁面,該頁面將該產品的所有詳細信息填入表單字段供用戶編輯。我的問題是,我怎樣才能編程角2?我在線看到的大多數示例都是在視圖的同一頁面(組件)上進行編輯。從角度2中的點擊事件將對象加載到窗體中

  • 我的項目結構:
    • 產品模型
    • product.service服務) - >會從REST風格的終點
    • 產品數據.component組件) - >負載的所有產品,並顯示在列表
    • edit.component組分) - >顯示從所選產品的所有數據,還使用反應形式使用角2 HTML內控制
    • 第4版

我想使用的端點(如/ api/product?id = xxx),但需要知道如何從product.component中選擇產品ID參數

謝謝!

+0

我在這裏看到類似於另一個問題的東西:https://stackoverflow.com/questions/35188060/send-string-value-to-component-on-url-navigation-in-angular-2(是的,我知道鏈接是不是最好的)。基本上它說@RouteConfig([ {component:MainComponent,path:「/:id」} ]),然後this.router.navigate(['../ Main',{id:2}]);, then導出類MainComponent {構造函數(params:RouteParams){ let value:any = params.get(「id」); } } - >感謝Vlado Tesanovic –

回答

1

按照您的建議使用端點是正確的方式去恕我直言。 爲此需要幾個步驟。

  1. 定義ID參數ProductComponent上點擊
const routes: Routes = [ 
    { path: 'products', component: ProductComponent }, 
    { path: 'products/:id', component: EditProductComponent } 
]; 

2.調用合適的路由

constructor(private router: Router, private service: ProductService) {} 

onClick(id: number) { 
    this.router.navigate(['products', id]); 
} 

3. EditProductComponent

找回ID從路由的路由
constructor(private activatedRoute: ActivatedRoute, 
    private service: ProductService) {} 

ngOnInit() { 
    const id = this.activatedRoute.snapshot.params['id']; 
    if (id) { 
    // get product data by calling endpoint with provided id 
    // e.g. this.service.getProduct(id).subscribe... 
    } else { 
    // throw some notification to user 
    } 
} 
相關問題