Angular2 通过service在组件(component)之间传递数据

2017-03-24阅读(8647)评论(0)牵着狗狗看MM

苏州实时公交查询

先看下routerTree,如下图
routertree
这里有个列表组件 和 详情组件,
假设,我在列表组件里点击某个按钮,把列表组件中的一个对象传递到详情组件,那么这个这个时候应该怎么去实现
我们先定义一个service data.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {  
  data:Object;
}

列表组件跟详情组件是在路由中是兄弟关系,app.routing.ts

import { RouterModule, Routes } from '@angular/router';

import { IterationListComponent} from './login/login.component';//列表组件
import { IterationDetailComponent} from './console/console.component';//详情组件

const routes: Routes = [
    { path: '', component: ConsoleComponent },
    { path: 'iteration', component: IterationListComponent },
    { path: 'iteration/detail/:id', component: IterationDetailComponent},
];

export const routing = RouterModule.forRoot(routes);

根组件,也就是列表组件跟详情组件的父组件app.component.ts

import { Component } from '@angular/core';
import { DataService } from './iteration-list/service/data.service';//这里在列表跟详情的父组件中引入DataService 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[DataService]//这里添加组件的providers元数据
})
export class AppComponent {

  constructor() { 
  }
}

在列表组件中iteration-list.component.ts

import { Component, OnInit, ViewChild, Input } from '@angular/core';

import { DataService } from './service/data.service';

@Component({
  selector: 'app-iteration-list',
  templateUrl: './iteration-list.component.html',
  styleUrls: ['./iteration-list.component.css'],
  providers:[]//注意在这里就不要再添加DataService 了
})

export class IterationListComponent implements OnInit {

constructor(
    private dataService:DataService//构造dataService
    ) { 
  }
ngOnInit() {}
clickDoSomeThing(item){
  this.dataService.data = {
    "iterationName":item['iterationName']
}
  this.router.navigate(['iteration/detail',item.id]);//点击后跳转到详情页 URL如http://localhost/iteration/detail/11 
  }

}

详情组件中iteration-detail.component.ts

import { Component, OnInit, ViewChild, Input } from '@angular/core';

import { DataService } from './service/data.service';

@Component({
  selector: 'app-iteration-list',
  templateUrl: './iteration-list.component.html',
  styleUrls: ['./iteration-list.component.css'],
  providers:[]//在这里也不需要添加DataService 
})

export class IterationListComponent implements OnInit {

constructor(
    private dataService:DataService//构造dataService
    ) { 
  }
ngOnInit() {
   console.log(this.dataService.data);//打印列表组件传过来的data
}


}

赞(0) 打赏
转载请注明来源:Web前端(W3Cways.com) - Web前端学习之路 » Angular2 通过service在组件(component)之间传递数据
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏