Exploring Observable Functionality in Angular 6

I've been grappling with understanding Angular Observables, but I've managed to get it working. My goal is to fetch data for my dynamic navigation bar. I successfully verified whether the user is logged in or not and displayed the Login or Logout button accordingly. However, I'm facing difficulty in retrieving user data. Here's my approach:

This is my User Interface:

interface User{
 status:boolean,
 username:string,
 email:string
 }

User service:

export class UserService {

private Userr :BehaviorSubject<User>

 constructor(private http:HttpClient) { 
this.Userr = new BehaviorSubject<User>({
  status:false,
  username:"",
  email:""  
});
}
setUser(user:User){
this.Userr.next(user);
 }
 get getUserData{
  return this.Userr.asObservable();
}
 get retrieveData{
return this.http.get<User>('/api/userdata')
}
}

Below is my navbar ts component implementation:

export class NavbarComponent implements OnInit {

isLoggedIn$: Observable<boolean>;        
 User$ : Observable<User>;
 constructor(private authService: AuthService,private router:Router,private 
 user:UserService) { }

 ngOnInit() {
 this.isLoggedIn$ = this.authService.getLoggedIn; 
 this.User$ = this.user.getUserData;
 }
 }

I chose not to include the logout function as I wanted to focus solely on fetching data. In the navbar html component, I have the following:

<a class="nav-link" (click)="logout()" routerLink='/welcome'>Welcome 
{{(User$ | async).username}}!, Log Out!</a>

However, the error I'm encountering is that User$.username is undefined. Thank you.

Edit For those facing a similar issue, here's how you can retrieve the username:

{{(User$ | async).username}}!

Answer №1

Absolutely, because the User$ is still an observable and has not completed its return yet. There are a couple of options:

1) Make use of Angular syntax to wait for the observable like this: {{ (User$ | async).username }}

2)

export class NavbarComponent implements OnInit {

isLoggedIn$: Observable<boolean>;        
 User$ : Observable<User>;
 user: User = {};
 constructor(private authService: AuthService,private router:Router,private 
 user:UserService) { }

 ngOnInit() {
 this.isLoggedIn$ = this.authService.getLoggedIn; 
 this.User$ = this.user.getUserData.subscribe(user => this.user = user);
 }
 }

{{user.username}}

To get the value from the observable, you can subscribe to it within a method and assign it to a user variable. Once the return happens, Angular will automatically update the DOM with the username value.

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

Input box in Angular matDatepicker fails when typing due to locale settings

When using a datepicker like this: <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker> ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

The benefits of a modular design in a React and TypeScript library

Following a tutorial on creating a library with React, Typescript, and rollup, I successfully managed to get everything working. However, as my project grows with additional features, I'm looking to have modular exports similar to what is seen in redu ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

Personalized information box utilizing Reactive Extensions in JavaScript

I am currently working on implementing a custom tooltip for a diagram using the vis-network library and RXJS. The key concept is to have: An observable named diagramElementHover$ to display the tooltip An observable named hideTooltipObs$ to hide the too ...

The duration of recorded audio in JavaScript is unclear

I managed to successfully create a structure for recording and downloading audio files. However, I'm facing an issue where the final downloaded file has an unknown duration. Is there any way to solve this problem?? Here is my Typescript code snippet: ...

Using TypeScript to work with asynchronous child_process.exec operations

Having trouble implementing a child_process.exec call with TypeScript and finding error handling to be quite challenging. Here's the basic idea of what I'm attempting: import { promisify } from "util"; import { exec, ExecException } fr ...

Using function overloading in TypeScript causes an error

I'm currently exploring the concept of function overloading in TypeScript and how it functions. type CreateElement = { (tag: 'a'): HTMLAnchorElement (tag: 'canvas'): HTMLCanvasElement (tag: 'table'): HTMLTableElem ...

Ensuring the correct type for an object's interface property value

I am currently working on defining a new interface interface SUser { ID: number; NAME: string; MAIL: string; PASSWORD: string; GENDER: number; BIRTHDATE: string; ID_FB: string; CREDIT: number; ID_REFERRAL: number; } My objective is to c ...

The functionality to automatically close the Material Sidebar upon clicking a navigation item is not functioning properly

After navigating by clicking on Sidebar nav items, I am trying to auto close the Material Sidebar. However, it doesn't seem to work in that way for me. I have created a Stackblitz to demonstrate my issue: Access the Stackblitz Editor Site here: http ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

What is the best way to utilize Typescript when making queries to Firebase?

I have successfully integrated push notifications for my app using Firebase Cloud Functions. Now, I am looking to enhance the user experience by updating the app's badge count alongside the push notifications. I understand that this can only be achiev ...

What is the reason for certain packages not being placed in the vendor folder during an Angular 2 installation?

I recently created a basic project in angular 2 using their cli. I noticed that when I use 'node install --save' for a material design project, the files are stored in both node_modules and dist/vendor directories. However, when I installed angul ...

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

Testing a Mocha import for a class from an unexported namespace

I'm in the process of creating unit tests for my Typescript application using the Mocha test framework. Within my web app, I have an internal module (A) that contains a class B. namespace A { export class B { constructor() { } ...

Inferring object types through direct values

This code example has a lot of detail: interface Coordinate { latitude: 40.7128; longitude: -74.0060; } const location: Coordinate = { latitude: 40.7128, longitude: -74.0060, }; // The inferred type would have been // { x: number; y: number; } I ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

Getting an Ionic 2 project up and running post git clone

After successfully creating an app using Ionic 2 Beta 7, I uploaded it to Github and cloned it into a different directory. Once in the new directory, I performed npm install and ionic state restore to install dependencies and added the android platform. ...

Receiving data from a service in Angular 2 with rxjs subscribe throws an error: it is not a

I've recently started working with Angular and I'm encountering an issue when trying to pass the _newArray to my child component using a shared service. Service fetchData(): Observable < any > { return forkJoin(this.fetchQuestions(), th ...

Personalized Titles for Angular Material Elements

I am new to using angular and angular material, and I find it a bit frustrating that each angular-material component starts with mat. For example: <mat-sidenav-container> <mat-sidenav>...</mat-sidenav> <mat-sidenav-content>...& ...