Troubleshooting: Service in Angular fails to communicate data

I am facing a challenge in using a service to enable communication between two components that are not directly related. I am unsure about how to utilize @Injectable and providedIn, which makes me think that the issue may lie there. However, everything I find online suggests that my implementation is correct. Due to the extensive length of my code files, which are nearly 1000 lines each, I have excluded a significant portion of the code. Apologies for any missing details, as I aimed to avoid including all those lines.

Below is the content of the service file where I store the data:

emailService.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({providedIn: "root"})
export class EmailFormatService {
  private videoMessage = new BehaviorSubject<string>("False");
  public message = this.videoMessage;

  public setVideoMessage(message: string) {
    console.log("set video");
    this.videoMessage.next(message);
  }

  public getVideoMessage() {
    return this.videoMessage;
  }
}

I use the setVideoMessage and getVideoMessage functions to manipulate the data. The parent file is where I attempt to modify the data within the service:

parentFile.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
...
import { MailConfigService } from './mail-config.service';

const CONTEXT = 'MailAddInService';

@Injectable({ providedIn: 'root' })
export class Parent {
  public constructor(
    private _emailService: EmailFormatService,
  ) {}

  public message?: string;

  public openDialogWindow(
    event: OpenDialogEvent | undefined,
    route: string,
    message?: string,
  ) {
    this._emailService.setVideoMessage("hello");
    Office.context.ui.displayDialogAsync(
      `${this._mailConfigService.environment.verbMail.addInUrl}/index.html#/${route}`,
    );
    }
  }

The child file is where I aim to retrieve the data. Here, the data always returns the value "False".

childFile.ts

public message!: string;

public constructor(
private _emailService: EmailFormatService,
) {

    this._emailService.getVideoMessage().subscribe(vidMessage => {
      this.message = vidMessage;
    });
}

childFile.html

<div>
 "Hi"
 {{message}}
</div>

The problem I am encountering is that even after setting the video message, the getVideoMessage still returns "False". It seems like it is accessing a different instance of the service.

Answer №1

After some thorough research, I managed to uncover the root cause of why this issue was occurring. It turns out that my usage of office.context.ui.displayDialogAsync() was creating a new instance on top of the host, causing all services to act as separate entities. To tackle this problem, I discovered that local storage and query parameters can serve as effective means of communication instead. For more information and detailed explanations, check out the following link:

https://learn.microsoft.com/en-us/office/dev/add-ins/develop/parent-to-dialog

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

Utilize ngclass in Angular 6 to dynamically apply two classes for enhanced rendering

There seems to be an issue with adding classes using ngclass and conditional class. It appears that only the last condition is working as expected. <div class="chat-box"> [ngClass]="{'chat': chat.type === 'chat', &ap ...

Sorting through an array of objects using a filter method

While following a tutorial, I decided to make some changes to the TypeScript for learning purposes. However, I encountered a problem when trying to create a filter function from a React context script. I have successfully implemented a function called get ...

Encountered in Angular 2: Uncaught error in promise - Type Error: Unable to access property 'setParent' of null

Out of nowhere, my component is throwing this error: "Uncaught (in promise): TypeError: Cannot read property 'setParent' of null" I'm going to create a plunkr to see if I can reproduce it. In the meantime, does anyone have any suggestions? ...

The CLI feature is not compatible with NextJS Drizzle-Kit

I'm currently utilizing the drizzle auth template and attempting to customize it for Role Based Authentication. I've made adjustments in the db.ts file to incorporate roles. import { drizzle } from 'drizzle-orm/postgres-js'; import { pg ...

Encountering an issue with the message: "Property 'ref' is not available on the type 'IntrinsicAttributes'."

Having trouble implementing a link in React and TypeScript that scrolls to the correct component after clicking? I'm using the useRef Hook, but encountering an error: Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assi ...

Ag-Grid filter not displaying

In my HTML file, I have the following code: <ag-grid-angular #agGrid style="height: 300px" [rowData]="rowData" [columnDefs]="columnDefs" [gridOptions]="gridOptions" ...

Do I need to use Node.js for Angular 2, or can I run it on an Apache server instead

Can XAMPP or Apache be used instead of the Node.js npm server when working with Angular 2? ...

Using ReactJS with Typescript and react rewired to load CSS module

I am currently setting up a proof of concept project using ReactJS and typescript, and I want to incorporate CSS modules without ejecting the webpack configuration. Here are the steps I have taken so far: Installed create-react-app globally - npm install ...

Self-sufficient API service and online platform

I recently developed an Angular 4 application independently in Node.js and created a rest api service using dropwizard. I attempted to connect the website as a static asset for the dropwizard service, but encountered integration issues. Despite exploring v ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

What is the best way to retrieve Express app configuration asynchronously?

I am utilizing an Express app developed with the Serverless Framework, which will be hosted via AWS API Gateway and AWS Lambda. The authentication process is handled by Okta, and I am considering storing the necessary secrets in SSM. Currently, I have to f ...

Is it possible to retrieve the original array after removing filters in Angular?

Within my component, I have an array that I am filtering based on a search string. The filtering works as expected when the user inputs characters into the search field. However, I am encountering an issue when attempting to display all records again after ...

What is the best way to incorporate additional data into a TypeScript object that is structured as JSON?

I'm exploring ways to add more elements to an object, but I'm uncertain about the process. My attempts to push data into the object have been unsuccessful. people = [{ name: 'robert', year: 1993 }]; //I aim to achieve this peopl ...

The Typescript compiler has trouble locating the definition file for an npm package

Recently, I released an npm package that was written in typescript. However, I have been facing difficulties in getting the definition recognized by typescript (webback and vscode). The only workaround that has worked for me so far is creating a folder wit ...

Creating a stationary Map in Typescript: A step-by-step guide

I am attempting to create a static Map that will store key value pairs with strings only. These values are meant to be constant and never change. Here is an example of what I'm trying to achieve: static KEY_VALUE_PAIR: Map<string, string>: { & ...

Stop the instantiation of type alias

Is there a way to restrict the creation of an instance of a type alias, such as ValidatedEmail? type ValidatedEmail = { address: string; validatedOn: Date } Let's say we have functions validateEmail and sendEmail. const validateEmail = (email): Valid ...

Exploring the concept of Anchors within the React

I am attempting to replicate a layout like this on my React frontend: <p> <h1>Foo</h1> <a href="#second"></a> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labo ...

What is the best way to append something to the textContent property of an HTML tag within a markup page?

While working on resolving an XSS vulnerability in the jqxGrid where the cell content is rendered as HTML, I encountered a scenario like this: <a href="javascript:alert('test');">Hello</a>. To address this issue, I am exploring ways t ...

Guide to retrieving Response Header in Angular 8 when making a POST request

Looking to fetch the response Header in Angular 8 after a post request and securely store the jwt token in localstorage? login(req): Observable<any> { return this.http.post(this.apiUrl + '/login', req).pipe( map(res => { if ...

Issue: The "target" key is deprecated and will not be recognized in next.config.js anymore

WARNING - The next.config.js file contains invalid options: The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devInd ...