background.js
在特定条件下获取数据。
-
当条件满足时,我激活
pageAction
-
"
和“background.js”回复我数据。
虽然我正在更新组件属性,但更改并没有反映UI。
背景.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse(this.data);
});
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 += ' !!';
}
}
应用程序组件.html
<div style="text-align:center">
<h1> Title: {{title}}</h1>
<h1> Response: {{response}}</h1>
</div>
<button (click)="clickMe()" >Click Me!</button>
就我而言,我正在从另一个范围更新app.component的属性,因为我无法实现数据的更改。
我已经添加了一个按钮,当我点击按钮时,“标题”字段已经改变,所以它更新了用户界面。
如何从其他上下文更新UI?
更新
因为在另一个范围内进行了更改,所以无法检测到更改,
所以我不得不强迫它:
constructor(private changeDetectorRef: ChangeDetectorRef) {}
ngOnInit() {
CHROME.runtime.sendMessage({
message: 'Give me data'
}, response => {
//...
this.changeDetectorRef.detectChanges();
});
}