Angular Chrome Api 数据绑定(bind)不起作用

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

我正在研究 chrome 扩展。我有一个 background.js 可以在特定条件下获取数据。

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

虽然我正在更新组件属性,但更改并未反射(reflect) 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();
    });
  }

最佳答案

我不太确定当所有内容都在同一个组件中时,为什么首先要使用 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;
    });
  }
}

关于Angular Chrome Api 数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174102/

相关文章:

html - Chartjs 和 Angular 5 上的错误 - "can' t 从给定项目获取上下文”

html - 为什么不工作

node.js - 如何输入自定义异步 Express 处理程序,以便透明地传递通用类型参数

javascript - 在Chrome扩展程序中将变量从popup.js发送到background.js

scripting - 访问 cookie ||来自内容脚本的 localSorage - Chrome 扩展

javascript - 将 CaptureVisibleTab 图像保存到临时文件以通过 Node.js 服务器发送

javascript - 默认 View 封装在 Angular 中是如何工作的

javascript - JSON 处理 - JavaScript

日期最小值的 Angular 自定义验证器

typescript - 如何在 Cypress 中将默认的 headless (headless)浏览器更改为 chrome