What is the best way to repurpose a variable in Angular's TypeScript?

I'm currently working on an application that utilizes the following technologies. In my Typescript file named "test.page.ts", there is a variable called "response: any" that I need to reuse in another Typescript file named "test2.page.html" by calling it as {{response.name}}. Can anyone guide me on how to accomplish this? Thank you.

Technologies I am using:

Ionic 4.10.2
Angular 6
8.1.2 (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e6eaf7e1eaf3e4a8e9ece7c5bdabb4abb4">[email protected]</a>)
TypeScript
Visual Studio Code

test.page.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { LoadingController, NavController, MenuController } from '@ionic/angular';

@Component({
  selector: 'app-test',
  templateUrl: './test.page.html',
  styleUrls: ['./test.page.scss'],
})
export class TestPage implements OnInit {

  response: any;
  searchTerm: any = '';

  constructor(private http: HttpClient, private loadingCtrl: LoadingController, private navCtrl: NavController) {
    this.getData();
  }

  ngOnInit() {
  }

  getData() {
    this.http.get('URL')
    .subscribe((response) => {
      this.response = response;
      console.log(this.response);
    });
  }
}

Answer №1

To achieve this, you can utilize the Subject feature. Below is a straightforward example to help you get started.

Here is the working stackblitz example: https://stackblitz.com/edit/angular-vts7zd?file=src%2Fapp%2Ftest.component.ts

App.Component.ts

export class AppComponent  {
  isEnglish = true;
  constructor(private service: CommonService){ }

  setLang(){
    this.isEnglish = !this.isEnglish;
    (this.isEnglish) ? this.service.setLang('IT') : this.service.setLang('EN');
  }
}

App.component.html

<span style="cursor:pointer" (click)="setLang()">Click me to change language</span>
<br><br>
<my-test></my-test>

The service

@Injectable()
export class CommonService{
  private lang$ = new Subject<string>();
  public langEvent = this.lang$.asObservable();

  public setLang(lang){
    this.lang$.next(lang);
  }
}

Test.Component.ts (it handles the data received from the subscription)

export class TestComponent implements OnInit  {
  lang ="default";
  constructor(private service: CommonService, private cdr: ChangeDetectorRef) {}

  ngOnInit(){
    this.service.langEvent
    .subscribe(res => {
      if(!!res){
        this.lang = res;
        this.cdr.detectChanges();
      }
    });
  }
}

The html

Current language : {{lang}}

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

The term "Exports" has not been defined

I'm currently facing a challenge trying to develop an Angular application based on my initial app. The process is not as smooth as I had hoped. Here's the current setup: index.html <!DOCTYPE html> <html> <head> <base h ...

The ngbDatepicker within the Bootstrap angular framework is designed to seamlessly integrate with ngbPanelContent without causing overflow issues

I've integrated the ngbDatepicker into a form as shown below <ngb-panel> <ng-template ngbPanelTitle> <div class="row"> <ui-switch (change)="onChange($event,2)" [checked]="profession ...

You should only call them after the method that returns a promise has completed

submitTCtoDB() { console.log("The selected file list contains: " + this.selectedFileList) this.readFile().then(() => { alert("ReadFile has finished, now submitting TC"); this.submitTC() }); } readFile() { return new Promise((resolve, r ...

`Is it possible to integrate npm libraries with typescript and ES6?`

I am looking to focus on using ES6 as the output for a node server-side app that I plan to run on the cutting-edge iojs distribution, which hopefully has support for the latest ES6 syntax. However, I'm unsure about how to integrate standard NPM libra ...

The compilation process encountered an error: TypeError - Unable to access property 'exclude' as it is undefined (awesome-typescript-loader)

After successfully converting my existing Angular 2 project into Angular 4, I encountered the following error: Module build failed: TypeError: Cannot read property 'exclude' of undefined For more details, please refer to the attached image bel ...

Monitor changes in Angular Reactive forms to retrieve the field name, as well as the previous value and the current value of the field

this.formData = this.fb.group({ field1: '', field2: '' }); this.formData.valueChanges.pipe(startWith(null), pairwise()) .subscribe(([previous, current]: [any, any]) => { console.log('PREVIOUS', previous); co ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Defined a data type using Typescript, however, the underlying Javascript code is operating with an incorrect data type

Recently delving into Typescript and following along with an educational video. Encountered a strange behavior that seems like a bug. For instance: const json = '{"x": 10, "y":10}'; const coordinates: { x: number; y: number } = JSON.parse(json); ...

Encountering an issue in Angular 8 flex-layout 8: Unable to export member ɵNgClassImpl

I encountered an issue while trying to install flex-layout 8.0.0-beta.26 in my Angular 8 project. The error I received during the build process is as follows: ERROR in node_modules/@angular/flex-layout/extended/typings/class/class.d.ts(9,19): error TS2305 ...

TypeScript primitive type is a fundamental data type within the

Does TypeScript have a predefined "primitive" type or similar concept? Like type primitive = 'number' | 'boolean' | 'string';. I'm aware I could define it manually, but having it built-in would be neat. ...

What are the best scenarios for implementing abstraction in Angular?

Throughout my experience, I have encountered Java EE, .Net, and various other enterprise application architectures. In each case, there was always an abstract upper class - like AbstractService for generalizing the service layer. However, in Angular, I ha ...

Is it possible to use Typescript to store and access static global variables based on a unique key

I want to store variables in a static global file, like this: declare const MYVAR = 'Some unchanging data'; Later on, I would like to be able to retrieve the information using just the key 'MYVAR', for example: globalFile.findValue ...

Tips for optimizing file sizes in an Angular 11 app for production deployment

Currently, I am troubleshooting an issue with my application where some of my production files are taking a long time to load. I have already deployed my application and tried using the --aot and optimizer commands during the production build process. Here ...

Ways to retrieve data object within an HTMLElement without relying on jQuery

Within my web application, I have successfully linked a jQuery keyboard to a textbox. Now, I am seeking a way to explicitly call the keyboard.close() function on the keyboard as I am removing all eventListeners from the text field early on. To achieve thi ...

Exploring Geographic Navigation with Angular Maps

Currently, I'm implementing Google Maps into my Angular SPA by following this helpful article. The HTML code in app.component.html looks like this: <html> <head> <meta charset="utf-8" /> <title>Map</titl ...

Organize data in the store using @ngrx/data and @ngrx/entity, rather than within the component (subscriber)

When working with the ngrx/data library, I often find myself having to manipulate and format data from the store in various parts of my application. While I have utilized the filterFn function to retrieve only the relevant entities for my use case, I am st ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Converting a string array to an object leads to an issue where the element implicitly has an 'any' type, as the expression of type 'string' cannot be used to index the type '{}'

Hey there, I have some code that looks like this: export type Options = Record<string, string> export type CheckboxValue<T extends Options> = Partial< Record<keyof T, boolean> > export type Checkbox<T extends Options> = ...

What is the best way to transfer information from the window method to the data function in a Vue.js application?

Is there a way to transfer information from the window method to the data function in a vuejs component? Take a look at my window method: window.authenticate = function(pid, receiptKey) { console.log("Authentication"); console.log(this) localStorag ...

Sign up for a service that sends out numerous simultaneous requests for every item in a list

I am encountering an issue with my Angular 5 component that is responsible for displaying a list of items. The items are fetched from a service and populated in the component by subscribing to the service. The service first makes a request to retrieve the ...