【发布时间】:2017-12-11 15:07:34
【问题描述】:
example.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class ExampleService {
number1 : number;
number2 : number;
result : number;
constructor() { }
}
component1.component.ts
import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'
@Component({
selector: 'app-component1',
templateUrl: './component1.component.html',
styleUrls: ['./component1.component.css'],
providers: [ExampleService]
})
export class Component1Component implements OnInit {
number1v = null;
number2v = null;
resultv = null;
constructor(public aService : ExampleService ) {
this.aService.number1 = this.number1v;
this.aService.number2 = this.number2v;
this.aService.result = this.resultv;
}
ngOnInit() {
}
processForm(){
this.resultv = this.number1v + this.number2v;
}
}
component2.component.ts
import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'
@Component({
selector: 'app-component2',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css'],
providers: [ExampleService]
})
export class Component2Component implements OnInit {
resultv;
constructor(public aService : ExampleService) {
this.aService.result = this.resultv;
}
ngOnInit() {
}
getResult(){
alert(this.resultv)
}
}
想要将结果值从组件 1 传递给组件 2。
没有父到子或子到父组件。
我得到的结果是未定义的。
【问题讨论】: