【问题标题】:Angular 2, change another component's view from unrelated componentAngular 2,从不相关的组件更改另一个组件的视图
【发布时间】:2017-02-04 23:22:05
【问题描述】:

我可以从另一个组件更改组件变量的值,如本例中的console.log() 所示。

我的问题是第二个组件的视图没有刷新,尽管变量发生了变化。

例子:

first.component.ts

import {Component} from '@angular/core';
import {SecondComponent} from './second.component';

@Component({
    selector: 'first',
    template: `
        <h2>First component</h2>
        <button (click)="changeOutside()">Change</button>
    `,
    providers: [SecondComponent]
})
export class FirstComponent {
    constructor(private otherComponent: SecondComponent) {}
    changeOutside() {
        this.otherComponent.change();
    }
}

second.component.ts

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

@Component({
    selector: 'second',
    template: `
        <h2>Second component</h2>
        <div>Pet: {{animal}}</div>
        <button (click)="change()">Change</button>
    `
})
export class SecondComponent {
    animal: string = 'Dog';
    change() {
        this.animal = 'Cat';
        console.log(this.animal);
    }
}

这两个组件完全不相关来自 DOM 树的不同分支。

我也试过第一个组件发出一个事件,第二个组件订阅它,结果相同,变量改变但视图没有更新。


Günter's suggestion(谢谢)之后,我尝试了下一个解决方案,但没有成功。即使console.log 也不起作用。

first.component.ts

import {Component} from '@angular/core';
import {UpdateService} from './update.service';

@Component({
    selector: 'first',
    template: `
        <h2>First component</h2>
        <button (click)="changeOutside()">Change</button>
    `
})
export class FirstComponent {
    constructor(private updateService: UpdateService) {}
    changeOutside() {
        this.updateService.changeAnimal('Cat');
    }
}

update.service.ts

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

@Injectable()
export class UpdateService {
    // Observable string sources
    private newAnimalSource = new Subject<string>();
    // Observable string streams
    newAnimal$ = this.newAnimalSource.asObservable();

    changeAnimal(animal: string) {
        this.newAnimalSource.next(animal);
    }
}

second.component.ts

import {Component} from '@angular/core';
import {UpdateService} from './update.service';
import {Subscription} from 'rxjs/Subscription';
import {Subject} from 'rxjs/Subject';

@Component({
    selector: 'second',
    template: `
        <h2>Second component</h2>
        <div>Pet: {{animal}}</div>
        <button (click)="change()">Change</button>
    `
})
export class SecondComponent {
    animal: string = 'Dog';
    subscription: Subscription;
    constructor(private updateService: UpdateService) {
        this.subscription = updateService.newAnimal$.subscribe(
            animal => {
                console.log(animal);
                this.animal = animal;
        });
    }
    change() {
        this.animal = 'Cat';
    }
}

已解决

最后,Günter 提出的解决方案在app.module.ts@NgModule 中添加UpdateService 作为provider 后奏效了

【问题讨论】:

    标签: angular components


    【解决方案1】:

    更新

    我很确定你的问题的原因是你所期望的

    constructor(private otherComponent: SecondComponent) {}
    

    做一些它实际上根本不做的事情。

    使用此构造函数,您将获得一个注入的SecondComponent 实例,该实例与您页面中显示的组件无关。这就是您的视图未更新的原因。您没有更新可见组件,而是更新了一个完全不相关的类。

    您需要使用不同的策略来获取对其他组件的引用。

    最好的方法是获取对组件的引用,而是向两者注入共享服务并使用可观察对象进行通信。

    更多详情请咨询this official angular 2 cookbook

    原创

    如果两个组件“完全不相关”,我认为这意味着它们来自单独引导的模块,因此位于同一页面上的不同 Angular2 应用程序中。

    在这种情况下,这些组件在不同的区域中运行,click 事件只会导致调用组件中的更改检测,而不是被调用组件中的更改检测。

    您需要在被调用者中显式调用更改检测以更新视图。比如像

    import {Component, ChangeDetectorRef} from '@angular/core';
    
    @Component({
        selector: 'second',
        template: `
            <h2>Second component</h2>
            <div>Pet: {{animal}}</div>
            <button (click)="change()">Change</button>
        `
    })
    export class SecondComponent {
        constructor(private cdRef:ChangeDetectorRef){}
    
        animal: string = 'Dog';
        change() {
            this.animal = 'Cat';
            console.log(this.animal);
            this.cdRef.detectChanges();
        }
    }
    

    import {Component, NgZone} from '@angular/core';
    
    @Component({
        selector: 'second',
        template: `
            <h2>Second component</h2>
            <div>Pet: {{animal}}</div>
            <button (click)="change()">Change</button>
        `
    })
    export class SecondComponent {
        constructor(private zone:NgZone){}
    
        animal: string = 'Dog';
        change() {
            this.zone.run(() => {
              this.animal = 'Cat';
              console.log(this.animal);
            });
        }
    }
    

    【讨论】:

    • 很抱歉我没有很好地解释自己。 完全不相关我试图反映他们不是彼此的父母或孩子。无论如何,我会尝试你的解决方案。谢谢。
    • 我的解决方案仅适用于不同的 Angular2 应用程序。
    • UpdateService 应该添加到 @NgModule(...) 装饰器的提供者中。在您的情况下,如果您将它添加到两个组件中,两个组件都会获得不同的实例。如果其中一个组件是另一个组件的父级,您也可以在父级only或作为两者的共同父级(祖先)的另一个组件处提供它。
    • 就是这样!,在app.module.ts 中添加了UpateService 作为@NgModule 的提供者,它可以工作。非常感谢您的准确和快速的答复。
    【解决方案2】:

    已解决

    正如我在问题中编辑的那样,Günter 提出的解决方案是第二系列文件,在 @987654324 的 @NgModule 中添加 UpdateService 作为 provider 后起作用@

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 2016-09-28
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多