经过一番艰苦卓绝的寻找,我终于在https://scotch.io/tutorials/get-angular-1-features-in-angular-2#toc-global-communication-with-services 找到了一个比较简单的解决方法,虽然我也不是太理解这个方法,不过能用。下面将我做的修改的文件列出来供你参考。此问题的解决还可以用一个些数据状态库。
// /home/yibingxiong/ng-plan/src/app/service/plan.service.ts import { Injectable } from '@angular/core'; import { Plan } from '../bean/plan'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export class PlanService { plans: Plan[]; totalTime = 0; totalTime$ = new BehaviorSubject<number>(this.totalTime); constructor() { this.plans = [ { id: 11, name: '大熊', date: 100000, totalTime: 1, comment: '学习到天亮' }, { id: 22, name: '大熊', date: 100000, totalTime: 1, comment: '学习到天亮' }, { id: 33, name: '大熊', date: 100000, totalTime: 1, comment: '学习到天亮' }]; this.totalTime = this.getTotalTime2(); } getPlans() { return this.plans; } // 添加计划 addPlan(newplan: Plan) { this.totalTime = this.getTotalTime2(); this.updateTotalTimeSbj(this.totalTime); this.plans.push(newplan); } // 删除计划 deletePlan(id: number) { let index = 0; for (let i = 0; i < this.plans.length; i++) { if (this.plans[i].id === id) { index = i; break; } } this.plans.splice(index, 1); this.totalTime = this.getTotalTime2(); this.updateTotalTimeSbj(this.totalTime); } // 获得一个计划 getPlan(id: number) { for (let i = 0; i < this.plans.length; i++) { if (this.plans[i].id === id) { return this.plans[i]; } } } // 计算计划总时间 getTotalTime2() { let t = 0; for (const p of this.plans) { t += p.totalTime; } return t; } get getTotalTime(): number { return this.totalTime; } private updateTotalTimeSbj(value) { this.totalTime$.next(value); } } // /home/yibingxiong/ng-plan/src/app/app.component.ts import { Component } from '@angular/core'; import { PlanService } from './service/plan.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private planService: PlanService) { } title = 'app'; } // /home/yibingxiong/ng-plan/src/app/app.component.html <app-navigation></app-navigation> <div class="container"> <div class="col-sm-3"> <div class="panel panel-default"> <div class="panel-heading"> <h1 class="text-center">已有时长</h1> </div> <div class="panel-body"> <h1 class="text-center">{{planService.getTotalTime}} 小时</h1> </div> </div> </div> <div class="col-sm-9"> <router-outlet></router-outlet> </div> </div> 12. 添加计划{ path: 'create', component: CreateComponent },
<a routerLink="/create">创建一个任务</a>
修改/home/yibingxiong/ng-plan/src/app/create/create.component.html
添加location依赖
在create组件注入并使用
在模板添加事件