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

Using Angular Material's [mat-form-field], you can easily input a value into a text box

How can I programmatically add a value to a text box within a [mat-form-field] using a function? addValueToTextBox(){ ... } ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

Setting the dispatch type in Redux using Typescript

I'm new to typescript and I'm trying to figure out what type should be assigned to the dispatch function. Currently, I am using 'any', but is there a way to map all actions to it? Here's how my code looks like: interface PropType ...

Issue encountered in Angular 2 while attempting to import TypeScript classes using a single file

Upon loading my Angular 2 application, I encountered the following error: EXCEPTION: Error: Uncaught (in promise): Unexpected piped value 'undefined' on the View of component 'DashboardComponent' An interesting observation is that by ...

Can Angular reactive forms be used to validate based on external conditions?

Currently, I am exploring Angular reactive forms validation and facing an issue with implementing Google autocomplete in an input field: <input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName ...

Understanding and parsing JSON with object pointers

Is it possible to deserialize a JSON in typescript that contains references to objects already existing within it? For instance, consider a scenario where there is a grandparent "Papa" connected to two parents "Dad" and "Mom", who have two children togeth ...

Are you looking for a streamlined method to create styled components with MaterialUI?

I am exploring ways to easily define convenient components in my application utilizing Material-UI. After referring to an example from the Material-UI documentation for Appbar, I attempted to incorporate some React components for better readability. My c ...

React Routing: Unleashing the Power of Multi-Level Routing

In my quest to create a route with multiple levels (<Route path="/hello/world" element={<a>hello world</a>} />), I encountered a few issues. Here are the versions I am using: react: 18.1 react-router-dom: 6.3.0 Success with O ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

SwitchMap in Typescript allows you to switch to a

In my TypeScript code, I have implemented multiple interfaces, components, and a key/interface map. interface FooProps { 'keyInFoo': string } const Foo = (props: FooProps) => {} interface BarProps { 'keyInBar': string } cons ...

Scrolling content with the mdldialogservice in Angular2

I am utilizing the MdlDialogService to trigger a help dialog from my home component: launchHelpDialog(){ this.dialogService.showCustomDialog({ component: HelpComponent, animate: true, isModal: true, styles: {'widt ...

Trouble arises when attempting to import React JSX project/modules from npm into an AngularJS TypeScript module

In the process of developing a proof-of-concept React framework/library, I aim to create a versatile solution that can be utilized in both React and AngularJS applications. To achieve this goal, I have initiated two separate projects: - sample-react-frame ...

When conducting a test, it was found that the JSX element labeled as 'AddIcon' does not possess any construct or call signatures

Here is a code snippet I'm currently working with: const tableIcons: Icons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />) }; const AddIcon ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Unable to display the attributes of an object using console.log

I am attempting to log the properties of an object in TypeScript, but I am encountering issues. setTitleAndBody(result: { title: String; body: String; }) { console.log(result) console.log(result.title) } What's interesting is that if I only l ...

When the Mat tab is clicked, the Expand Collapse feature associated with it will be displayed

Currently, I am implementing Mat tabs (vertical) in one component and Mat expand/collapse functionality in another component. Upon clicking on a tab, the corresponding Mat expand should be displayed. You can view the progress of my work on this Stackblitz ...

Bundle Angular library exports along with its corresponding models

I am in the process of developing an angular library for our company's private npm repository. Within this library, I aim to export classes that are utilized (injected via @Input()) in the library components. Here is a sample model: export class AdsT ...

Update a particular form field value prior to submission

Currently, I am working on a User registration page that includes the functionality for users to upload their own avatar picture. My approach involves uploading the picture, then calling a function on change to convert the picture into a UInt8Array before ...

The unit test ends right before reaching the RxJS skipWhile method

of({loadstatus: Loaded}) .skipWhile(user => user.loadStatus !== Loaded) .take(1) .subscribe(user => do some stuff) I am puzzled by why a unit test is not triggering the skipWhile function in the code snippet above. When I set a breakpoin ...