Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable:

      private _user = new BehaviorSubject<ApplicationUser | null>(null); 
      user$ = this._user.asObservable();

The ApplicationUser model is defined as:

    export interface ApplicationUser {
      userName: string;
      role: string;
    }

I understand how to access user$ in the template with:

    <li *ngIf="authService.user$ | async as user ; else login">
                  <a href="#" data-uk-icon="user">{{ user.userName }}</a>              
                </li>

However, I aim to manipulate it within my component. I have attempted:

    user!: ApplicationUser;
    
      ngOnInit(): void {
    
        this.authService.user$      
          .subscribe((test: ApplicationUser) => {
            this.user = test; 
          });
    }

I have also tried:

    this.user=this.authService.user$.subscribe();

This results in an error stating that Subscription is missing required properties (username, role).

Another attempt was:

    this.authService.user$
          .subscribe(test=> this.user = test);

However, a complaint arises indicating that Type 'ApplicationUser | null' cannot be assigned to type 'ApplicationUser'.

What should be the appropriate syntax in my component to store the observable data into my user variable?

Thank you

Answer №1

One way to enhance the subscription emitted value is by including a ! at the end:

this.userService.data$.subscribe((result) => this.data = result!);

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 two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables? I attempted the following, but it did not function as expected <ul id="example-1"> <li v-for="apple in apples" v-for="banana in bananas"> {{ apple .message }} {{ banana .message }} & ...

Upon the initial loading of GoJS and Angular Links, nodes are not bypassed

Hey there, I'm currently working on a workflow editor and renderer using Angular and GoJS. Everything seems to be in order, except for this one pesky bug that's bothering me. When the page first loads, the links don't avoid nodes properly. H ...

Customizing the width of the JQuery $ui.progressbar by overriding its properties

After spending some time, I successfully overrode the function that controls the width of the progress bar element in the jQuery UI widget version 1.12.1 from September 14, 2016. Initially, I needed the progress bar to completely fill a column in a table. ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

display a container and navigate to the specific link

Greetings! Could someone please help me make this code function properly? I am attempting to display the DIV (slidingDiv) and navigate to the selected ANCHOR (#anchor-01 + #anchor-02 + #anchor-03)... However, the code currently only allows me to go to the ...

Building Silent Authentication in React Native with the help of Auth0: A Step-by-Step Guide

I am currently working on my first React Native app, and I have integrated Auth0 for authentication purposes. My goal is to implement silent authentication using refresh tokens. So far, I have attempted to use the checkSession() method but encountered an ...

Steps for Implementing an Event Listener in JavaScript

While working on a page in Chrome, I encountered an issue where I wanted a modal to show up when a user clicked on an image. However, the functionality was not working as expected on my localhost. Upon further inspection, I believe there might be a problem ...

I have encountered an issue while utilizing dynamic form functionality in Angular 7. The error message displayed is: "Error: Cannot find control with name: 'i'"

While working with Angular 7 dynamic forms, I encountered an error that I'm struggling to resolve. As a newcomer to Angular, this has been quite challenging for me. import { Component } from '@angular/core'; import {FormBuilder, FormArray} ...

Unable to initiate a new project in Node.js

As I was working on adding a new project in Angular, everything was running smoothly until today. However, when trying to create a new project today, I noticed that the node_modules folder is missing and encountered the following errors: https://i.stack.i ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...

Display a pop-up window when hovering over a table cell using HTML and JavaScript

I am currently developing a JavaScript application and came across a helpful library called qtip2. My objective is to have different information displayed when the user hovers over each cell in the table. The qtip2 library I mentioned earlier can display ...

Attempting to update information in JSON using AJAX and PHP

I am attempting to update key values in a JSON object using PHP, AJAX, and JavaScript to display the new values. Here is an example of my JSON database that needs to be modified: "answer01count": "1", "answer02count": "2", "answer03count": " ...

tips for efficiently using keyboard to navigate through tabs in an unordered list

Utilizing unordered lists in this web application. I am looking to implement tab navigation with keyboard functionality. How can I achieve this? The first tab should contain text boxes, and when the user fills out a text box and presses the tab key, they s ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

Issues encountered while setting up @angular/google-maps on angular13

Every time I attempt to install, this error displays: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="402d21306d212323 ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

Moving various divisions through Javascript by clicking various buttons although sharing the same identifier

I am working with the script below: $(document).ready(function() { $('.expandButton').click(function() { $('.expandableSection').toggle("slide"); }); }); My goal is to apply this script to multiple sections. However, ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

The external javascript file is unable to recognize the HTML table rows that are dynamically inserted through an AJAX request

I have a situation where I'm pulling data from an SQL database and integrating it into my existing HTML table row. Here's the code snippet: Using Ajax to fetch data upon clicking analyze_submit: $(document).ready(function(e) { $('#anal ...

The 'ObjectID' property is not present in the 'CollectionStatic' data type

Encountering an issue with the MongoDB npm module: mongoId = new Mongo.Collection.ObjectID()._str; Attached is a screenshot for reference. Appreciate any assistance. ...