【发布时间】:2019-04-09 23:25:28
【问题描述】:
我正在开发 chrome 扩展。我有一个background.js 来获取特定条件下的数据。
- 当条件满足时激活pageAction
- 当用户点击扩展图标时,我正在向
“
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