Угловое связывание данных Chrome Api не работает - PullRequest
0 голосов
/ 06 ноября 2018

Я работаю над расширением Chrome. У меня есть background.js для получения данных в определенных условиях.

  1. Когда выполняются условия, активируется действие pageAction
  2. К тому времени, когда пользователь нажимает значок расширения, я отправляю сообщение "background.js" и "background.js" отвечают мне данными.

Хотя я обновляю свойство компонента, но это изменение не отражает пользовательский интерфейс.

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 Detect, поле «title» было изменено, поэтому оно обновляет пользовательский интерфейс.

Как я могу обновить пользовательский интерфейс из другого контекста?


Обновление

Из-за изменений, внесенных в другом объеме, Angular не смог обнаружить изменения, поэтому я должен заставить его:

constructor(private changeDetectorRef: ChangeDetectorRef) {}

  ngOnInit() {
    CHROME.runtime.sendMessage({
      message: 'Give me data'
    }, response => {
      //...
      this.changeDetectorRef.detectChanges();
    });
  }

1 Ответ

0 голосов
/ 06 ноября 2018

Я не совсем уверен, почему вы используете 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;
    });
  }
}
...