Issue
I'm new to angular and I'm trying to assign null value for replysubject in angular . I exactly wrote my code from tutorial but i wonder why i cant assign null value for this kind of object. Here's my code from my service class.
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);**** this line won't compile
}
}
Solution
- The
mapoperator must return something. If not it might returnundefinedto the subscribers. You're better off using thetapoperator here seeing there are no response transformations required.
login(model: any): Observable<User> {
return this.http.post<User>(this.baseUrl + 'account/login', model).pipe(
tap((response: User) => {
const user = response;
if (user) {
localStorage.setItem('user',JSON.stringify(user));
this.currentUserSource.next(user);
}
})
);
}
- About the error, most probably the tutorial was written pre-Angular Ivy. With Ivy AoT enabled, the values pushed must conform to the types defined. In your case you're pushing
nullto observable of typeUser. You could either disable Ivy or use union types to also acceptnull.
private currentUserSource=new ReplaySubject<User | null>(1);
Answered By - ruth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.