gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:19 25 4
gpt4 key购买 nike

我正在研究 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com