In Angular, a variable that is exported from a module may not be accessible within a class function

Within my Angular project, I have a service file where I export a variable to be used in another file (component.ts).

Interestingly, when I access the value of this variable outside of the class, everything works as expected. However, if I try to access it within any function declared inside the component class, I encounter an error stating that the variable is not defined.

As every module in Angular has its own scope and TypeScript files are converted into JavaScript with classes becoming functions, I expect variables outside of functions to be available. Strangely, though, assigning the variable to a declared variable outside the class seems to resolve the issue.

I am puzzled by this behavior. Can anyone help me understand what I might be missing?

import {UserService ,b} from './services/user.service';
console.log(b); // This works
// var t = b; // Also working

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[UserService]
})
export class AppComponent implements DoCheck, AfterContentInit, AfterContentChecked {
  title = 'project';
  a:any = "joshi";
  
  constructor(private vc: ViewContainerRef, private user: UserService) {
    console.log("parent constr");
  }

  update() {
    // t = "changed"; // This works
    // b = "changed"; // Does not work
    this.user.setObservable();
  }
}

Answer №1

It is not feasible to change a variable outside of a module as it is treated as immutable, similar to a const. However, if the variable was an object like

export let b = { name:  "shashank" };

you would have the ability to modify it.

An alternative solution could be creating a function within the module itself that allows you to update its value, such as:

export let b = "shashank";

export let setB = (value) => {
  b = value;
}

and in the component:

update(){
  setB("Hero");
  console.log(b)
  this.user.setObservable();
}

However, it appears there might be a flaw in your approach. Since b is located inside the UserService, it can be accessed using this.user.b instead of importing it explicitly.

The method you are currently utilizing seems incorrect (unless there are additional details not provided in your question)

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

Managing a Angular HTTP Request on a Bottle Server where CORS is restricted

I am encountering an issue while trying to send data from my Angular 9 App to a bottle backend server. When running the application on the client side, I receive a CORS (Cross-Origin Resource Sharing) error indicating that the 'Access-Control-Allow-Or ...

Angular 6 Observer - Double Authentication Triggered

I am currently learning about Observer and Http requests. My code is functioning properly, but it lacks elegance and the issue I am facing is that the URL is being called twice. isAuthenticated() { let obs = this.http.get('http://localhost:8080/a ...

What is the method for accessing JSON data?

Looking for assistance on a coding issue I'm facing. I need my JavaScript code to read JSON data and grant access to a staff panel based on the information provided. Below is the sample JSON: { "User1": { "User": " ...

Is the dragging behavior of a rotated image different than that of the original image when using CSS rotation?

While working on a CSS grid to showcase images rotated at 60 degrees for a diagonal view, I encountered an issue. I wanted users to have the ability to drag and drop images within the grid, but when they drag an image, it moves as if it weren't rotate ...

I'm experiencing an issue with this code where it is returning the URL instead of the expected data

const http = require('http'); const xml2js = require('xml2js'); const parser = xml2js.Parser({ explicitArray: false }); const goodreadsService = function () { const getBookById = function (id, cb) { const options = { ...

Leveraging the ng-template in a broader context

I need to create a recursive menu from JSON data with a specific structure. The JSON looks like this: this.menus = [{ "id": 1, "title": "Azure", "class": "fa-cloud", "url": "#", "menu": [{ "id": 121, ...

Deduce the Prop Component Type by Examining the Attribute Type

I am facing an issue with a component that requires a `labels` attribute. <Component defaultValue={FURNITURE.BED} labels={[ { value: FURNITURE.BED, text: 'Bed', }, { value: FURNITURE.COUCH, text: 'C ...

Angular4 micro front-end development allows for a modular and scalable approach

Our application is made up of several services, with an edge service handling routing and load balancing for all requests to the individual services. The backend REST API is successfully deployed on each server, but we face a challenge with our single Ang ...

The Flux Router in React Native

I am diving into the world of React Native and currently working on creating a practice app. The issue I'm facing is with the routing functionality in my project. At the moment, I have three main components: the app itself, the router component, and o ...

Initial value not being recognized by mat-input attribute disable

My current challenge involves toggling the enable/disable status of mat-inputs based on a specific property value within an object. Within my component, I am subscribing to an observable in my service that retrieves applications with a default disabled fl ...

Issue with React / Express failing to route links accurately

Currently, my React project is functioning well except for Express. I have been struggling to find comprehensive tutorials on implementing correct routing with Express in a MERN stack application. I have come across some Stack Overflow posts, but none of ...

Query executed but no results returned

Currently, I am practicing GQL and facing an issue when trying to display data in the Playground. I am attempting to access the jsonplaceholder API to fetch all posts and show them, but encountering the following error: Error: GRAPHQL_FORMAT_ERROR: Expec ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

Having difficulty executing the Cypress open command within a Next.js project that uses Typescript

I'm having trouble running cypress open in my Next.js project with Typescript. When I run the command, I encounter the following issues: % npm run cypress:open > [email protected] cypress:open > cypress open DevTools listening on ws: ...

The absence of the Three.js file in my HTML file is noticeable

Currently, I am diving into HTML5 and experimenting with the Three.js 3D engine. While following a tutorial from this source, it was recommended that I include the three.js file in my HTML document. However, I encountered two files with the same name and d ...

Creating a suggestion box within an HTML container using JavaScript

https://i.sstatic.net/Asi5r.pngI am currently working on a page where users can click on a word and receive a small suggestion box (like a tiny popup) to choose synonyms they prefer. Although I believe this can be achieved with JavaScript, I haven't ...

Redirecting pages without a hash portion

In my Express.js app.js file, there is a get route that looks like this: app.get('/admin', function(req, res, next){ if(req.isAuthenticated()) { return next(); } res.redirect('/admin/login'); },Routes.Admin.Index); When a ...

Utilize the power of Angular 12 and Bootstrap 5 with the ability to load multiple imported scss theme files

I'm currently incorporating Angular 12 and Bootstrap 5 into my project. For loading Bootstrap, I have imported it from my SCSS file along with three theme SCSS files. This is how it appears: style.scss: @import './assets/styles/theme1.scss&apo ...

Step-by-step guide to retrieving the value of a duplicate input field with identical IDs in Angular4

This is the form I am working on: <button (click)="M_add()">Add</button> <tbody id="_tbody"> </tbody> Whenever the add button is clicked, it triggers the creation of an input field. let tbody = document.getElementById("_tbody"); ...

Dealing with unsuccessful http puts in an Angular4 application

I'm interested in finding best practices for managing a failed PUT HTTP request within Angular4. Here's the scenario: a basic component is trying to update a record by making an API call with a put request. Below are some example code snippets: ...