我正在研究 chrome 扩展。我有一个 background.js
可以在特定条件下获取数据。
- 当条件满足时,我会激活 pageAction
- 当用户点击扩展图标时,我正在向
“
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/