【问题标题】:Angular Chrome Api Data Binding Not WorkingAngular Chrome Api 数据绑定不起作用
【发布时间】:2019-04-09 23:25:28
【问题描述】:

我正在开发 chrome 扩展。我有一个background.js 来获取特定条件下的数据。

  1. 当条件满足时激活pageAction
  2. 当用户点击扩展图标时,我正在向 “background.js”和“background.js”用数据回复我。

虽然我正在更新组件属性,但更改并未反映 UI。

background.js

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  sendResponse(this.data);
});

app.component.ts

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


// @ts-ignore
const CHROME = chrome;


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

  title = 'Title';
  response: any;

  constructor() {}

  ngOnInit() {
    CHROME.runtime.sendMessage({
      message: 'Give me data'
    }, response => {
      this.title = response.title;
      this.response = JSON.stringify(response);
      console.log(response.title);
    });
  }

  clickMe() {
    console.log('Before:' + this.title);
    this.title +=  ' !!';
  }
}

app.component.html

  <div style="text-align:center">
   <h1> Title: {{title}}</h1>
   <h1> Response: {{response}}</h1>
  </div>

<button (click)="clickMe()" >Click Me!</button>

就我而言,我正在从另一个范围更新 app.component 的属性,因为 Angular 无法实现数据更改。

我在单击按钮时添加了一个按钮 Angular 检测到“标题”字段已更改,因此它会更新 UI。

如何从另一个上下文更新 UI?


更新

由于更改已在另一个范围内进行,Angular 无法检测到更改, 所以我必须强迫它:

constructor(private changeDetectorRef: ChangeDetectorRef) {}

  ngOnInit() {
    CHROME.runtime.sendMessage({
      message: 'Give me data'
    }, response => {
      //...
      this.changeDetectorRef.detectChanges();
    });
  }

【问题讨论】:

  • 你试过用箭头函数语法代替thisthat吗?
  • 是的,我现在尝试了,但结果相同,数据在控制台中,但 UI 没有更新。
  • 问题解决了,我要强制Angular去detectChanges,来源:stackoverflow.com/a/35106069/7885651

标签: angular typescript google-chrome-extension data-binding observable


【解决方案1】:

当您将所有内容都放在同一个组件中时,我不确定您为什么首先使用Subject。尝试摆脱它并使用ngOnInit 而不是constructor

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

// @ts-ignore
const CHROME = chrome;

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

  title = 'Title';
  response: any;

  constructor() {}

  ngOnInit() {
    CHROME.runtime.sendMessage({
      message: 'Give me data'
    }, response => {
      this.title = response.title;
      this.response = response;
    });
  }
}

【讨论】:

  • SiddAjmera 我已经更新了这个问题,你能帮帮我吗:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2020-06-28
  • 2017-12-15
  • 2015-06-19
  • 2018-02-12
  • 2015-11-07
相关资源
最近更新 更多