【问题标题】:Passing a user defined number between component through service angular 2通过服务角度2在组件之间传递用户定义的数字
【发布时间】: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。

没有父到子或子到父组件。

我得到的结果是未定义的。

【问题讨论】:

标签: angular angular2-services


【解决方案1】:

问题在于,当组件 A 更新服务时,组件 B 不知道这些更改。所以,为了解决这个问题,我们需要使用观察者模式,让所有观察者都知道变化。

幸运的是 Angular 自带了 rxjs,所以我们可以使用BehaviorSubject 来实现观察者模式。

服务代码

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

@Injectable()
export class ExampleService {

    number1 = new BehaviorSubject<number>(0);
    number2 = new BehaviorSubject<number>(0);
    result = new BehaviorSubject<number>(0);
    constructor() { }

}

在组件内部你可以读取它们的值

service.number1.subscribe(num => {
   // ....
});

要更改任何数字,您可以通过这种方式更新它

service.number1.next(1); // set new number 

当然这是粗略的方式,您可以通过阅读在线教程或 BehaaviorSubject 上的答案获得更好的示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-13
    • 2018-10-03
    • 2019-09-25
    • 2020-09-12
    • 2017-08-23
    • 1970-01-01
    • 2016-07-12
    • 2018-12-31
    相关资源
    最近更新 更多