Troubleshooting Data Binding Issues in Angular with Chrome's API

I'm currently developing a Chrome extension that utilizes a background.js file to fetch data under specific conditions.

  1. When these conditions are met, I activate the pageAction
  2. Upon clicking the extension icon, a message is sent to "background.js" and the response contains the requested data.

Despite updating the component property, the changes aren't immediately reflected in the 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>

I have discovered that due to the nature of updating app.component's property from another scope, Angular struggles to recognize these changes and update the UI accordingly.

To address this issue, I included a button that triggers an update in Angular when clicked, allowing for proper UI updates.

Is there a way to ensure the UI updates automatically without manual intervention?


Update

Because Angular couldn't detect the changes made in another scope, I had to explicitly trigger an update:

constructor(private changeDetectorRef: ChangeDetectorRef) {}

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

Answer №1

It seems unnecessary to use a Subject when all the data is already in the same Component. Consider removing it and utilizing the ngOnInit method instead of the 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;
    });
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Exploring the process of retrieving URL parameters within an activated link using Angular 7 and executing a REST API call from a service

My aim is to retrieve data by utilizing the id field through Get parameters. Below is the URL code in my HTML that redirects to a specific page without triggering the service to fetch the REST API. <a [routerLink]="['/usedCars/detail', list ...

Tips for providing all props to a React component while still including necessary props specified in an interface

Am I overlooking something or is this a different issue altogether? import * as React from 'react'; interface Props { value: string; } const MyComponent = (props: Props) => { const { value, ...rest } = props; return ( & ...

Exploring Service Injection and Factory Pattern in Angular 8

After going through various articles and official Angular guides, it appears that they were unable to assist me in solving my task. Here's what I wanted to achieve: Imagine having an Angular application with a product listing page. Additionally, this ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab. This is my userlog.component.ts file: import { Component, OnInit, O ...

Display an image in Angular by uploading it to your application

Seeking assistance for a private project involving Angular 13 with PHP and MySQL. After successfully setting up communication between these technologies to upload recipe information to the database, I am facing challenges with uploading recipe images. Whil ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...

Execute the function once Router.navigate is completed

Is there a way to execute a specific function after a user successfully logs in, regardless of which page they logged in from? The goal is to redirect the user back to their previous browsing page upon login. I've been using Router.navigate for URL r ...

Can a lifecycle hook be interrupted in Angular 2?

Is there a way to prevent a Lifecycle Hook in angular2 from running when a specific variable becomes true? I have searched for information on this topic without success, but I believe it would be a great feature to have. ...

Having trouble looping through an array in Angular 2?

I am currently using a FirebaseObjectObservable to retrieve the value of a property from my firebase database. The property can have multiple values, so I stored them in a local array variable. However, I ran into an issue while trying to iterate through ...

Utilizing Visual Studio Code for setting breakpoints in Typescript Jasmine tests

Currently, I am in the process of configuring a launch setup in Visual Studio Code for debugging my unit tests. The unit tests are written in Typescript, and both the tests and the corresponding code are compiled into a single js file with a source map. ...

The service function is not defined

I am currently working on implementing an async validator in Angular using devextreme components. To do this, I created a service with a function and imported it into the relevant component. In the constructor of the component, I defined a property and cal ...

Tips for addressing the ExpressionChangedAfterItHasBeenCheckedError issueWould you like a way

I comprehend the reason for this error occurring in dev mode and the underlying cause. (for those who are unsure: ExpressionChangedAfterItHasBeenCheckedError Explained) What perplexes me is how to rectify it in my specific scenario. I am displaying a hi ...

What is the best way to instruct TypeScript to utilize a globally installed NPM @types package?

After running npm install @types/node, the TypeScript compiler worked perfectly with tsc -p tsconfig.json. However, when I attempted to install the package globally with npm install -g @types/node and deleted the local folder, I encountered the following ...

Retrieving data from an API using VUEJS3 and Typescript

I am facing an issue with displaying data in my template. When I try to do so, the screen remains blank. I am using Vue.js 3 with TypeScript and I am fairly new to this technology. <template> <div> <img :src="datas[0].imag ...

Sharing JSON data between components securely without displaying it in the URL through routing

Seeking to pass JSON through routing URL, my code in app.route.ts looks like this: {path: 'calculator', component: CalculatorComponent,data : {some_data : null}}, The code used to route the data is as follows: this.router.navigate(['/home ...

Encountered issues with the BsModalService in displaying the modal functionality

I am encountering an issue while attempting to display a modal using a service. When I call the service from a button, everything works fine. However, I encounter an error when calling it from an error handler. TypeError: Cannot read property 'attach ...

VueJS - When using common functions, the reference to "this" may be undefined

I'm struggling to extract a function that can be used across various components. The issue is that when I try to use "this", it is coming up as undefined. I'm not sure of the best practice for handling this situation and how to properly assign th ...

Jest encountering errors when compiling a generic function

I'm able to successfully run my Node app, but running tests on a class with Generics is causing an error. The test code looks like this: import { Request, Response } from 'express'; import { JsonWebTokenError } from 'jsonwebtoken' ...

Tips for preventing words from being split between lines in an error message

I am encountering a problem in Angular 2 where error messages are being split onto two lines when there isn't enough space for the entire word. Check out this screenshot for reference Is it possible to prevent words from being divided across lines? ...