There is no matching overload for this call. The first of three overloads is, '(obj: Observable<unknown>'

Attempting to implement a basic login/logout feature using Angular as the frontend, I encounter an obstacle when utilizing observables. The error appears in nav.component.html:

https://i.sstatic.net/kCBDo.png

Here is the code snippet:

nav.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from '../_models/user';
import { AccountService } from '../_services/account.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {

  model : any = {};

  currentUser$:Observable<User>;
 

  constructor(private accountService : AccountService) { }

  ngOnInit(): void {
    this.currentUser$=this.accountService.currentUser$;
  }

  
//corresponding codes
  

 

}


accountservice.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../_models/user';

@Injectable({
  providedIn: 'root'
})
export class AccountService {

  baseUrl='https://localhost:5001/api/';
  private currentUserSource =new ReplaySubject<User> (1);
  currentUser$=this.currentUserSource.asObservable();

  

  constructor(private http :HttpClient) { }

  login(model:any)
  {
    return this.http.post<User>(this.baseUrl+'account/login',model).pipe(

      map((response:User)=>{

        const user=response;
        if(user){
          localStorage.setItem('user',JSON.stringify(user));
          this.currentUserSource.next(user);
        }
      })
    )
  }



  setCurrentUser(user:User)
  {
    this.currentUserSource.next(user);
  }





  logout()
  {
    localStorage.removeItem('user');
    this.currentUserSource.next(null as any);
  }
}


nav.component.html

//corresponding codes


  <form *ngIf="!currentUser$ | async" #loginForm="ngForm" class="d-flex"  (ngSubmit)="login()" autocomplete="off">
          <input 
          
           name="username"
           [(ngModel)]="model.username"
           class="form-control me-2"
           type="text"
            placeholder="username">

          <input 

            name="password"
            [(ngModel)]="model.password"
          
            class="form-control me-2"
            type="password"
            placeholder="Password">

          <button class="btn btn-outline-success" type="submit">LOGIN</button>
        </form>
      </div>
    
  </nav>


Being new to Angular, seeking guidance on resolving this issue. Any help would be appreciated.

Answer №1

Instead of utilizing

*ngIf="!currentUser$ | async"
in the condition, you can replace it with either
*ngIf="(currrentUser$ | async) === null"
or
*ngIf="!(currentUser$ | async)"
to check for the presence of a current user in the variable currentUser$ or null.

Answer №2

In order to properly use the not-operator in this context, we must surround (currentUser$ | async) with parentheses and then check if the current user is equal to null. By removing the not operator and utilizing three equals signs instead, we can determine if we are indeed equal to null. Therefore, the corrected answer is:

(currentUser$ | async) === null

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

Various approaches to declaring a function in TypeScript

Within my TypeScript module, I have the following code snippet: import app = require("durandal/app"); import ko = require("knockout"); class Screen1 { method1(arg: string): string { return "Hello"; } method2 = (arg: string): string = ...

Issue with Google Oauth2 authentication not providing Refresh token after successful authentication

When creating an authentication module for my Angular2 Web application using the Oauth2 Google+ API, I encountered an issue with the Google server response. Despite adding parameters to the POST query and attempting to revoke access and try again, the resp ...

Tips on sorting an array within a map function

During the iteration process, I am facing a challenge where I need to modify certain values based on specific conditions. Here is the current loop setup: response.result.forEach(item => { this.tableModel.push( new F ...

What are the steps to showcase the content of a Typescript file on an HTML webpage?

We are looking to create a sample gallery with source code examples. Including typescript, html, and HTML files to showcase similar to the Angular.io component samples pages. Is there a way to extract the source code from a typescript file within our pro ...

Error message: "ExpressionChangedAfterItHasBeenCheckedError - encountered while using ngIf directive to hide/show a progress

My HTTP interceptor is set up to display a loading bar whenever an HTTP request is made: intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const dataStorageService = this.injector.get(DataStorageService); ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

TypeScript operates under the assumption that every key will be present on a Record object

Check out this code snippet: declare const foo: Record<string, number> const x = foo['some-key'] TypeScript indicates that x is of type number. It would be more accurate to say x is of type number | undefined, as there is no guarantee th ...

Error: nativeElement.getBoundingClientRect method is undefined

While working on my application test, I encountered a challenge when trying to validate the returns of two getBoundingClientRect functions. The first one, which is in an HTMLElement located by ID, gave me no trouble as I was able to mock its return success ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

What methods do typescript libraries use to interpret types during runtime?

After compiling source code from TypeScript to JavaScript, type annotations are removed and it becomes impossible to verify the type of a variable at runtime. Despite this limitation, there exist TypeScript libraries that alter their behavior based on the ...

What is the best way to empty session storage in Angular when the browser tab is closed?

Every time I access my browsing history, it automatically logs me in. However, if I try to enter the URL in a new tab, I am redirected to the login page. I have already attempted to clear the session by using browser tab close events. // 1 @HostListener(&a ...

Clearing Out a Shopping Cart in Angular

Hey there, I have a little dilemma with my shopping cart system. I can easily add and delete products using an API. However, when it comes to deleting an item from the cart, I have to do it one by one by clicking on a button for each item, which is not ver ...

Is there a shortcut for creating interfaces that have identical sub properties?

We are seeking to streamline the interface creation process by utilizing shorthand for properties labeled from Monday through Sunday, each with identical sub-properties. interface Day { start: number end: number } interface Schedule { Monday: Day ...

Executing a function using an interface parameter along with other types in a method

Is there a way to design an interface with this structure? export interface GenericType<T> { (data: T): void; hasLimit?: boolean; } The question now arises, how do I provide an object that adheres to this interface? One solutio ...

Subscribing to valueChanges in reactive forms to dynamically update checkbox options

My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes. cars = [ { id: 1, na ...

Library for injecting dependencies - changing the names of injected variables

Is there a way to inject lodash by a different name using ES6/ES7/ES8 or TypeScript? let val = function(lodash){ // lodash will be injected, simply by using require('lodash'); }; What if I want to rename the import? Can I do something like t ...

Unable to locate module within Typescript

Hello everyone, I am facing a problem similar to this one: I have an app written in TypeScript, and within it, I have imported import { Component } from '@angular/core'; import {CORE_DIRECTIVES} from '@angular/common'; import { MODA ...

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

A guide on transforming a 1-dimensional array into a 2-dimensional matrix layout using Angular

My query revolves around utilizing Template (HTML) within Angular. I am looking for a way to dynamically display an array of objects without permanently converting it. The array consists of objects. kpi: { value: string; header: string; footer: string }[] ...

Tips for writing an async function using TypeScript

I've been working with Typescript and NLP.js. However, I'm encountering an issue where the argument manager is displaying 'Parameter manager implicitly has an any type'. I attempted to use :, but it didn't solve the problem eff ...