angular 2 unsubscribed variable becomes null

I'm having an issue with calling a service in my component, causing the data to always go null. Here is an example of the code:

The service method :

getOneUser() {
    return this._http.get(globals.serverIp + '/user/getOneUser/' + this._ls.getCurrentUserName(), { headers: this.headers})
      .map((response: Response) => <UserParser> response.json());
  }

The method in the component :

updateParametre(message: string){
    let currentUser = new User();

    this._us.getOneUser().subscribe(
      data =>currentUser = data.data,
      error => console.log('error from updateParam ParamtereComponenet ' + error),
      () => console.log(currentUser)
    );
let anotherinstance : User = currentuser ;
console.log(currentUser);
  }

Attempting to console log the currentUser inside the subscribe method:

    {id: 9,
 initials: "YCI",
 nom: "CHABLI",
 prenom: "Yassin",
 password: "$2a$10$iWVnXs/2TwOk7CBr5RuQ.e/1c/BTlxsvkjHyYrtOgKUiRMll2EupO"}

However, the object `anotherintance` becomes null, and trying to console log the `currentUser` outside of the subscribe also results in null.

What could be causing this issue? Please help.

Answer №1

anotherInstance is confined to the scope of that function. To have access to it, you must declare it outside of that particular scope.

The subscribe method works asynchronously. When you set anotherInstance to currentUser, currentUser only holds a new User() at that moment. As a result, it will become undefined once the function is finished executing.

Maintain appropriate variable scopes and assign values when you actually obtain the necessary data:

anotherInstance: User;

updateParametre(message: string){
    let currentUser = new User();

    this._us.getOneUser().subscribe(
      (data) => { 
         currentUser = data.data,
         this.anotherInstance = currentUser
      }
      (error) => console.log(`error from updateParam ParamtereComponenet: ${error}`),
      () => console.log(currentUser)
    );
  }

As a result, anotherInstance becomes a property of your class and can be accessed beyond the confines of the updateParameter method.

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

Error message 'No suitable overload for this function' occurs while attempting to retrieve a Map

While attempting to generate a Map, I encounter an unfamiliar error message that is puzzling: TS2769: No overload matches this call. Overload 1 of 4, '(iterable: Iterable<readonly [string, number]>): Map<string, number>', gave the f ...

Tips for expanding a child route to occupy the entire page within a nested route in Angular

I'm facing an issue with my parent and child routes in my project. I have a parent route labeled PRODUCTS and a child route named CREATE-PRODUCT. The problem arises when the user clicks on the CREATE-PRODUCT button - instead of navigating to the creat ...

What is the best way to restore mat-select to its original state when clicked?

I am currently utilizing mat-select along with mat-option, and I am looking to reset the selected mat-option when a button is clicked. Instead of simply setting its value to null, my goal is for the option without a value to be visible on the screen. For ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

There seems to be a glitch in the input found within the form array

Check out this Stackblitz demo Have you noticed a bug where the input loses focus when typing? Additionally, there seems to be a limit of only 4 symbols that can be typed. Any suggestions on how to fix this issue would be greatly appreciated. Thank you! ...

Dealing with a Typescript challenge of iterating over a tuple array to extract particular values

I am struggling with writing a function that extracts names from an array of tuples, where each tuple includes a name and an age. My current attempt looks like this: type someTuple = [string, number] function names(namesAndAges: someTuple[]) { let allNa ...

Utilizing dynamic CSS classes within an ngFor loop

Struggling with my pure CSS star rating implementation, specifically with the hover effect. When hovering on one rating star, the behavior affects the first or all five stars of the previous question. https://i.sstatic.net/cpjvw.png In the provided image ...

Implement Bootstrap into Asp.Net Core 6 for the scaffolded Identity _Layout.cshtml

In my development environment using VS2022 Preview, I have set up a Single Page Application with Angular and the default project provided by VS2022. To customize the appearance of the Identity pages, I decided to override Bootstrap with a style from Bootsw ...

Strange Typescript Issue: Dependency Imports Not Recognized as Top-Level Module

Attempting to move a custom token from one account to another by following this detailed tutorial. Facing an issue with four errors showing up for all imports from the @solana/spl-token package. Tried removing the node-modules folder and reinstalling npm ...

Having trouble obtaining search parameters in page.tsx with Next.js 13

Currently, I am in the process of developing a Next.js project with the Next 13 page router. I am facing an issue where I need to access the search parameters from the server component. export default async function Home({ params, searchParams, }: { ...

Is there a way to align cards to stack on both the right and left sides of each other?

I need to create a card that includes text and an image, save it as a component, and then display this component three times in app.component.html so that the cards are all visible on the website. Currently, the cards are stacked vertically. How can I alig ...

Tips for testing nested subscribe methods in Angular unit testing

FunctionToTest() { this.someService.method1().subscribe((response) => { if (response.Success) { this.someService.method2().subscribe((res) => { this.anotherService.method3(); }) } }); } Consider the following scenario. ...

Unable to access /route upon refreshing page in Angular 7

After developing several components in Angular 7, I decided not to use 'useHash: true' for routing. Everything seemed to be running smoothly when I deployed my Angular app on a live server. However, I encountered an issue when reloading a page a ...

Utilize external libraries with Angular 2 for Just-In-Time and Ahead-of-Time compilation techniques

I've been working on setting up my codebase to support both JiT and AoT compilation in order to utilize JiT for local development and AoT for production. Following the Angular documentation, I have successfully configured both modes individually. How ...

"Array.Find function encounters issues when unable to locate a specific string within the Array

Currently, I am utilizing an array.find function to search for the BreakdownPalletID when the itemScan value matches a SKU in the array. However, if there is no match found, my application throws a 'Cannot read property breakdownPalletID of undefined& ...

Is there a beginner's pack or trial version available for utilizing TypeScript with IBM Cloud Functions / OpenWhisk?

While working on developing actions in IBM Cloud Functions, I have been primarily using Node.js / Javascript and Python for coding. However, I haven't come across specific instructions on how to incorporate TypeScript into IBM Cloud Functions. I am c ...

What is the abbreviated method of setting a default value for an optional String in Swift?

After receiving a variable from a network call of type optional String, const receivedData = data.receivedData Is there a shortcut method to construct a String using this variable and provide a default value when it's null? const finalString = "Rec ...

Guide on showing error message according to personalized validation regulations in Angular 2?

Utilizing a template-driven strategy for constructing forms in Angular 2, I have successfully implemented custom validators that can be utilized within the template. However, I am facing an issue with displaying specific error messages associated with dis ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

Resolving Angular 4 issue by delivering Observable of an array of strings

The error "Type 'Observable<{ "aa": any; "dd": any; "cc": any; }>' is not assignable to type 'Observable'." is popping up in my Angular 4 project. How can I resolve this issue with the syntax? Any suggestions on fixing this err ...