代码之家  ›  专栏  ›  技术社区  ›  Muhammed Ozdogan

Angular Chrome Api数据绑定不工作

  •  1
  • Muhammed Ozdogan  · 技术社区  · 6 年前

    background.js 在特定条件下获取数据。

    1. 当条件满足时,我激活 pageAction
    2. " 和“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();
        });
      }
    
    1 回复  |  直到 6 年前
        1
  •  -1
  •   SiddAjmera    6 年前

    我不知道你为什么要用 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;
        });
      }
    }