Encountering an undefined value in Angular outside of the subscription

I am facing an issue where I need to use the value from the user outside the subscribe function in order to assign it to my tweet class. However, when I try to print it outside the subscribe function, it shows as undefined. Can anyone provide a solution for this?

Below is my code snippet:

entities

export class Tweet {
    id: number;
    created_at: Date;
    message: string;
    updated_at: Date;
    user: User;

    export class User {
    id?: number;
    username?: string;
    password?: string;
    email?: string;
    imageUrl?: string;
    accountType?: string;
}
}

service

export class UserService {

  private apiServerUrl: string;

  constructor(private http: HttpClient) { 
    this.apiServerUrl = environment.apiBaseUrl;
  }
 public findUserById(userId: number): Observable<User> {
    return this.http.get<User>(`${this.apiServerUrl}/user/${userId}`);
  }

  createTweet(tweet: Tweet) : Observable<Tweet> {
    return this.http.post<Tweet>(`${this.url}/tweet`, tweet);
  }
}

component

 user: User = new User();
    getUser() {
      const id = sessionStorage.getItem('userId');
      this.userService.findUserById(+id).subscribe(response => {
        this.user = response;
        console.log(this.user);
      });

    }


    tweet: Tweet = new Tweet();
    createTweet() {
      this.tweet.message = this.tweetForm.get('text').value;
      this.tweetService.createTweet(this.tweet).subscribe(response => {
        this.tweet = response;
        this.tweet.user = this.user;
      });

    }

Answer №1

sendTweet(): Observable<yourDataType> {
  this.tweet.message = this.tweetForm.get('text').value;
  return this.tweetService.sendTweet(this.tweet);
}

fetchUserDetails() {
  const id = sessionStorage.getItem('userId');
  this.userService.getUserById(+id).pipe(
    tap((response) => this.user = response),
    switchMap(() => this.sendTweet()) 
  )
  .subscribe((tweetResponse) => {
    this.tweet = response;
    this.tweet.user = this.user;
  });
}

Alternatively, using forkJoin:

sendTweet(): Observable<yourDataType> {
  this.tweet.message = this.tweetForm.get('text').value;
  return this.tweetService.sendTweet(this.tweet);
}

fetchUser(): Observable<anotherDataType> {
  this.tweet.message = this.tweetForm.get('text').value;
  return this.tweetService.sendTweet(this.tweet);
}

someAction(): void {
  const userAndTweet = forkJoin({
    user: this.fetchUser(),
    tweet: this.sendTweet()  
  });

  userAndTweet.subscribe(values => {
     this.user = values.user;
     this.tweet = values.tweet;
     this.tweet.user = this.user;
  });
}

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

Retrieving a specific item using its ID from a JSON file with Ionic 5

Newcomer's query For multiple Ionic pages, I require fetching a specific item by ID from a centralized JSON file. The structure of my JSON data is as follows: { "items": [ { "id":"0", "link&q ...

I am currently working to resolve this particular wildcard issue with the help of TypeScript

I've been working on solving the wildcard problem with TypeScript, but I'm running into issues with some of the test cases I've created. Here's a brief overview of how the code operates: A balanced string is one where each character ap ...

Best practices for transferring date objects between a frontend developed in JavaScript/TypeScript and a backend built in ASP.net Core 5

An exciting project I am working on involves a web application with a backend REST web API developed in ASP.net Core 5 and a frontend Angular application written in TypeScript. One of the APIs from the ASP.net backend returns an instance of a C# object de ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

TypeScript failing to recognize dependency for LitElement

Currently, I am encountering an issue with importing two lit elements in my project, namely RootElement and CustomElement. The problem arises when trying to import CustomElement, which unlike RootElement does not show up properly on the UI. My attempt to i ...

The FormGroup instance does not return any input method when using the get input function

I am facing an issue where a custom error message should only display if the input for foo is invalid. However, it seems like the line of code myForm.get('foo') is returning null. Below is the simplified version of component.html: <form [for ...

Encountering an issue while trying to deploy my node.js application on Heroku

While monitoring the Heroku logs using the command heroku --tail, I encountered the following error: Error: 2022-01-25T19:10:06.153750+00:00 app[web.1]: at emitErrorCloseNT (node:internal/streams/destroy:122:3) 2022-01-25T19:10:06.157055+00:00 heroku[rout ...

The development mode of NextJS is experiencing issues, however, the build and start commands are functioning normally

Just finished creating a brand new Next app (version: 12.0.7) using Typescript and Storybook. Everything seems to be working fine - I can successfully build and start the server. However, when I try to run dev mode and make a request, I encounter the follo ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Assigning styles and values to an object using ngStyle

Within my component, I am encountering an issue where I am trying to edit some styles on a different component. I am passing an object to the component through property binding. The problem arises when updating the BorderRadius - it works when declaring a ...

Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below: import { suite, test, slow, timeout, skip, only } from 'mocha-typescript&apo ...

Redirect to the homepage if the requested page is not found in IIS

Within my IIS Website, there are three applications being hosted. The main website is an Angular App, alongside an API application housing all APIs and another application that is a pure javascript project hosted under the application alias /vmenu/. Any r ...

What is the method for developing a Typescript-connected High-Order React Component with Redux?

I am looking to develop a React Higher-Order Component that can safeguard routes within my application from unauthorized users without an access token. I aim to use this HOC to wrap a Component like so in the parent component: <Route exact path ...

Angular 6 - Ensuring all child components are instances of the same component

My issue has been simplified: <div *ngIf="layout1" class="layout1"> <div class="sidebar-layout1"> some items </div> <child-component [something]="sth"></child-component> </div> <div *ngIf="!layout1" class= ...

Encountering an issue with the Angular router-outlet: Unable to find any matching routes for the specified

I must apologize as I have searched extensively for a solution to my problem, but unfortunately, I have not been successful despite numerous attempts. Currently, I am working with Angular version 13.3.9 I am attempting to utilize the outlet router functi ...

The valueChanges event of a Reactive Form is activated whenever options from a datalist are selected

Whenever a user types into the input field, I am making an API call to retrieve and display data in a datalist for autocompletion (typeahead). control.get('city').valueChanges.pipe( map((searchText) => searchText.trim().toLowerCase()), fi ...

A guide to creating test cases for conditional statements in Angular using Jasmine

I am currently working on creating test cases for a custom directive in Angular. I have shared my code on StackBlitz. I would appreciate any guidance on how to address the highlighted if else statements below: if (trimmedValue.length > 14) { // Loo ...

Guide to incorporating a pluck feature into TypeScript code

One task I face frequently is extracting specific properties from an object const obj = {a:1, b: 2, c: 3}; const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2} Unfortunately, achieving this task with type safety in TypeScript can be c ...

Setting up APIGateway for CORS with the CDK: A Step-by-Step Guide

My API relies on AWS ApiGateway with an underlying AWS Lambda function provisioned through the CDK. The default CORS settings for the API are as follows: const api = new apiGateway.RestApi(this, "comments-api", { defaultCorsPreflightOptions: { ...

Utilizing nested objects in ngrx/store effects

Currently, I am in the process of learning Angular 2 and experimenting with ngrx/store. However, I am encountering some challenges when it comes to dealing with certain special cases. For instance, one issue I am facing is attempting to remove a parent ob ...