数据绑定失败,因为变量不更新其值

问题描述 投票:0回答:2

我有这个'错误'消息组件。它使用数据绑定来获取其文本,因此我只创建了一个函数,该函数将应该显示的消息作为参数。这是个主意:

<div id="success"> {{message}} </div>

组件:

  message: string = "Something went wrong";

  constructor() { }

  ngOnInit() {
  }

  callMessage(msg: string) {
    this.message= msg;
    $("#success").animate({
      'top': '10px'
    });
  }

你看,message从任何调用它的人那里获得它的价值。问题是在callMessage()函数中,值确实会更新,但全局变量不会更改。我在网上看了这个,并尝试了像window.messagewindow[message]这样的东西,但它们似乎都没有用。我也尝试删除固定的消息'出错了',但变量只是保持为空。我也试过从ngOnInit调用函数,但没有成功,我无法删除callMessage()并将其粘贴到ngOnInit中,因为它不接受参数。

这导致消息组件始终显示固定消息(或没有它,没有它)。有趣的是,这应该工作。在这个相同的项目中,我做了许多其他功能,通过改变全局值,并将它传递给DOM。但由于某种原因,这个例子似乎失败了。

可能是什么导致了这个?

注意:如果您需要任何其他代码,请随意说出来,只是为了澄清,callMessage()在web-app的主要ngOnInit中调用

编辑:有人要求装饰者,所以这里看起来更好看:

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.css'],
  providers: [MessagesComponent]
})
export class MessagesComponent implements OnInit {

这就是我所说的:

ngOnInit() {

  this.toggleSuccess('Test');

}

toggleSuccess(msg: string) {

  this.messagesComponent.callMessage(msg);

}

当然,我在main.html中有一个<app-messages></app-messages>

obs:那些是分离的方法,因为我通常从main调用toggleSuccess,而不是将消息扩展到完整的项目(因为已经提供了mainComponent)

angular typescript global
2个回答
1
投票

正如@Arif在评论中所说,你的做法是错误的。

有两个单独的实例。显示的内容与提供的内容无关。

在其他选项中,您可以使用单例服务方法:StackBlitz演示(这是最好的解决方案imho)。


1
投票

你的方法不正确。你不应该注入组件。

你应该做的是:

要么 - 使用@ViewChild并仅在ngAfterViewInit中或之后调用它

或 - 创建服务,并使用ComponentFactoryResolver动态插入视图。

或者 - 创建单例服务(在root中提供),创建行为,从错误组件中侦听该主题。

@Injectable({
    provideIn: 'root'
})
export class ErrorService {
    public error = new BehaviourSubject(null);
}

将其注入app.component并发送消息

constructor(private errorService: ErrorService) {

}

ngAfterViewInit() {
    this.errorService.error.next('Your message');
}

在您的app-error组件中执行此操作

  message: string = "Something went wrong";

  constructor(private errorService: ErrorService) { }

  ngOnInit() {
    this.errorService.error.subscribe(error => {
      if (error !== null) {
        this.callMessage(error);
      }
    })
  }

  callMessage(msg: string) {
    this.message= msg;
    $("#success").animate({
      'top': '10px'
    });
  }

注意:请重新检查我的代码是否有拼写错误,因为我正在使用手机写这个。

© www.soinside.com 2019 - 2024. All rights reserved.