没有重载匹配这个调用。重载 1 of 3, '(obj: Observable<unknown>

时间:2021-05-27 06:46:11

标签: angular typescript asp.net-core rxjs

我正在尝试使用 angular 作为字体和创建一个简单的登录注销实现。当我开始使用 observable 时,我被卡住了。这是我在 nav.component.html 中的错误:-

enter image description here

这是我的代码。

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$;
  }

  
//clarify code
  

 

}


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

//clarify code


  <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>


我是 Angular 的绝对初学者。我如何解决这个问题。请帮忙。

2 个答案:

答案 0 :(得分:0)

在 if 语句中不使用 *ngIf="!currentUser$ | async" 将其替换为 *ngIf="(currrentUser$ | async) === null"*ngIf="!(currentUser$ | async)" 以了解变量 currentUser$null 中是否存在当前用户.

答案 1 :(得分:0)

您不能像这样使用这个非运算符,因为它不起作用。我们要做的是将这个(currentUser$ | async)括在括号中,然后我们要做的是检查当前用户是否等于null。所以我们需要去掉not操作符,然后我们只用三个equals来看看我们是否等于null,而不是在这里使用not操作符。因此答案是

(currentUser$ | async) === null