Authorization Token getting sent as null in the Response in Angular - javascript

I am trying to work with REST API's provided within my Enterprise Application and Angular. What I am trying to achieve is to fetch some data from my Enterprise Application. For this I have to do two things:
1- Login to my Enterprise Application via Angular. For doing so, there's already a custom authentication REST API provided by the Enterprise Application. I am consuming the same. An authentication token is generated which I am saving within localStorage.
2- Send a GET request to the Enterprise Application to fetch data after Authentication happened. This is where I am facing issues. I am unable to pass the authentication token within the GET Request. On Checking the same under "Application" Tab of Chrome Dev Tools, I Could see under "Request Headers" Section that Authorization value is null. Below is the screenshot of the same:
Below is my code that I have developed:
1 - Authentication Service (auth.service.ts)
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import{Http} from '#angular/http'
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { URLSearchParams,Response } from '#angular/http'
#Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
username:string = 'Admin';
password:string='livelink';
token:any;
login()
{
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('Username', this.username);
urlSearchParams.append('Password', this.password);
this.http.post('http://localhost/otcs/cs.exe/api/v1/auth',urlSearchParams)
.subscribe((res:Response) =>
{
// login successful if there's a jwt token in the response
if (res) {
const data = res.json();
;
this.token = data;
console.log(data);
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ ticket: data }));
}
});
console.log("INSIDE LOGIN this.token = "+this.token)//done for debugging, returning undefined
}
public getToken()
{
console.log("GET TOKEN VALUE "+ localStorage.getItem('ticket'))//done for debugging, returning undefined
return localStorage.getItem('ticket');
}
}
2 - Token Interceptor (token.interceptor.ts)
import { Injectable } from '#angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '#angular/common/http';
import { AuthenticationService } from './auth.service';
import { Observable } from 'rxjs';
import { Http } from '#angular/http';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
3 - App Component (app.component.ts)
import { Component } from '#angular/core';
import { AuthenticationService } from './auth.service';
import{Http} from '#angular/http'
import { HttpClient } from '#angular/common/http'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
constructor(private authenticationService: AuthenticationService, private
http:HttpClient)
{
this.authenticationService.login();
this.ping() ;
}
public ping() {
this.http.get('http://localhost/otcs/cs.exe/api/v1/nodes/16236/output')
.subscribe(
data => console.log(data),
err => console.log(err)
);
}
}
4- App Module (app.module.ts)
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from
'#angular/common/http';
import { AppComponent } from './app.component';
import { AuthenticationService } from './auth.service';
import { HttpModule } from '#angular/http';
import { TokenInterceptor } from './token.interceptor';
#NgModule({
declarations:[AppComponent],
imports: [
BrowserModule,
HttpClientModule,
HttpModule
],
providers: [AuthenticationService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
On running the above project, below is the output displayed in Console:
I am unable to understand as to why is my token not getting passed with the GET Request.

You are saving the token using this line
localStorage.setItem('currentUser', JSON.stringify({ ticket: data }));
But, your function getToken() is getting it wrong from localStorage. I think your function should look like:
public getToken() {
const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
console.log("GET TOKEN VALUE ", currentUser.ticket))//done for debugging
return currentUser.ticket;
}
Hope it helps

While retrieving the token in getToken, use the key as "currrentUser" instead of "ticket"
public getToken() {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser) {
return currentUser.ticket;
} else return null;
}
Better to store the key in some config so its accessible everywhere hence no missing on current key.

Related

How can I get my user data and send it to a component?

I have an application using laravel as backend and Angular in frontend.
What I want to do is to get the user data and output it anywhere on my website. For example I would like to get the name for the user and output it on the homepage when the user is logged in.
I can successfully register and log in a user. I can get the user data from my login method in the authService in the console.log. But how can I use that user data and get the user data from my getUser method? Is there any way for me to send the data from login method to the getUser method?
authService
import { Injectable } from '#angular/core';
import { User } from '../shared/user';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse
} from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
endpoint: string = `${environment.RECIPE_LIST_API}`;
headers = new HttpHeaders().set('Content-Type', 'application/json');
currentUser = {};
constructor(private http: HttpClient, public router: Router) {}
// Log in
login(user: User) {
return this.http
.post<any>(`${this.endpoint}/login`, user)
.subscribe((res: any) => {
console.log(res);
localStorage.setItem('access_token', res.token);
this.currentUser = res;
});
}
getUser() {
this.currentUser
// want to get my userdata here so that I can send it to any component
}
}
component that I want to send my data to
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { AuthService } from '../services/auth.service';
#Component({
selector: 'app-recipe-lists',
templateUrl: './recipe-lists.component.html',
styleUrls: ['./recipe-lists.component.css']
})
export class RecipeListsComponent implements OnInit {
currentUser: Object = {};
constructor(
public authService: AuthService,
private actRoute: ActivatedRoute
) {
this.authService.getUser();
}
ngOnInit(): void {}
}
user.ts
export class User {
email!: String;
password!: String;
}

Calling HTTPS API from Angular deployed in http server

I am calling HTTPS API from Angular service deployed in http server by the following code.
this.chatbotUrl = "https://something.com/api";
getDashBoardData(): Observable<any> {
return this.http.get<IContainer>(this.chatbotUrl+"/chatbot/get-dashboard-data").pipe(
map((response) => (response ? response : {})),
catchError( this.handleError )
);
}
But when I am calling this API, then I am getting this error, "Http failure response for https://something.com/api/chatbot/get-dashboard-data: 0 Unknown Error". The following error is also get.
GET https://something.com/api/chatbot/get-time-wise-traffic/7 net::ERR_CERT_COMMON_NAME_INVALID
How can I call https API from Angular service deployed in http server?
I suppose you have not configured the API properly,check whether the site requires any key to get accessed.Here I have provided the component.ts file and service file for the API I am working with for your reference.
If CORS error try adding CORS extension to your browser;else clear your cache and run your code again.
Component.ts:
import { Component, OnInit } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
import { YoutubeService } from '../youtube.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
Name:any;
details: any;
info:any;
display!:boolean;
constructor(private service:YoutubeService,public sanitizer: DomSanitizer) { }
ngOnInit(): void {
this.service.GetVideos().subscribe((res:any)=> {
this.info= res as any
this.info=this.info.items;
console.log(this.info);
this.display=true
});
}
onSubmit() {
this.service.GetSearch(this.Name).subscribe(res=> {
this.details= res as any
this.details=this.details.items;
// this.details.forEach((function.this.details.i) => {
// ele
// });
console.log(this.details);
this.display=true
});
}
}
Service:
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { GoogleLoginProvider } from 'angularx-social-login';
#Injectable({
providedIn: 'root'
})
export class YoutubeService {
private APIURL = "https://youtube.googleapis.com/youtube/v3/";
private APIKEY ="AIzaSyB40HaKwd0VggftBq8R9sEwQx_NG5xOOWc";
constructor(private http:HttpClient) { }
public GetSearch(name:string)
{
console.log(name)
return this.http.get(this.APIURL+"search?part=snippet&key="+this.APIKEY+"&q="+name+"&type=video");
}

How to resolve ERROR NetworkError at XMLHttpRequest.send (...dist\fxcore\server\main.js:200768:19)

I am new to Angular. I just finished developing my angular web application. When I use ng serve to serve my application during production, everything works fine. I added angular universal. Now when I run any of npm run dev:ssr or npm run build:ssr && npm run serve:ssr, my application will refuse to open, throwing NetworkError response in the console. I noticed this error occurs for the number of times http requests where sent via class 'constructors(){..}'. I have browsed through several solution but couldn't get a clue of what I'm not doing right. My backend is developed with nodejs and express. I'll appreciate any help I can get.
Here is a full example of the error response I always get in the console.
ERROR NetworkError
at XMLHttpRequest.send (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:200768:19)
at Observable._subscribe (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:19025:17)
at Observable._trySubscribe (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:186304:25)
at Observable.subscribe (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:186290:22)
at scheduleTask (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:105897:32)
at Observable._subscribe (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:105959:13)
at Observable._trySubscribe (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:186304:25)
at Observable.subscribe (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:186290:22)
at subscribeToResult (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:196385:23)
at MergeMapSubscriber._innerSub (C:\Users\MRBEN\Desktop\Angular\fxcore\dist\fxcore\server\main.js:191575:116)```
I was still getting this ERROR NetworkError but I found another way to make this error go away. I think this answer is relevant since I was getting the same error posted above. If this can help anyone with that same server error then that's great.
If the api request is made to the server OnInit when reloading check isPlatformBrowser first when using ng-universal example.
import { Component, OnInit, PLATFORM_ID, Inject } from '#angular/core';
import { isPlatformBrowser } from '#angular/common';
import { HttpClient, HttpHeaders } from '#angular/common/http';
export class HomeComponent implements OnInit {
public testBrowser : boolean;
public data : any;
constructor(private http: HttpClient, #Inject(PLATFORM_ID) platformId: string) {
this.testBrowser = isPlatformBrowser(platformId);
}
ngOnInit() {
if (this.testBrowser) {
//avoid server NETWORK error
this.data = this.http.get('/api');
}
}
}
I was getting this same error trying to make server calls from the client before checking isPlatformBrowser === true first OnInit and this solved my problem. Hopefully this can help this bug.
For reference this answer helped me squash this long standing bug. https://stackoverflow.com/a/46893433/4684183
I am getting the same error. Try to remove TransferHttpCacheModule from your app.module and create your own custom http transfer interceptor file.
I made a file called transfer-state.interceptor.ts and then added it to app.module providers:[] to handle this. The examples below will show how I hooked it up. I am not sure if this will definitely work for you but it did make that error go away for me.
//app.module.ts
import { BrowserModule, BrowserTransferStateModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from "#angular/common/http";
//import {TransferHttpCacheModule } from '#nguniversal/common';
import { AppRoutingModule } from './app-routing/app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './modules/home/home.component';
import { SliderComponent } from './components/slider/slider.component';
import { WindowRefService } from './services/window-ref.service';
//import { TransferHttpInterceptorService } from './services/transfer-http-interceptor.service';
import { TransferStateInterceptor } from './interceptors/transfer-state.interceptor';
import { ServiceWorkerModule } from '#angular/service-worker';
import { environment } from '../environments/environment';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
SliderComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
BrowserTransferStateModule,
AppRoutingModule,
HttpClientModule,
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
],
providers: [
WindowRefService,
{
provide: HTTP_INTERCEPTORS,
useClass: TransferStateInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
This is one version of a custom transfer state file but there are a few ways to do this if this one doesn't work.
//transfer-state.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '#angular/common/http';
import { Inject, Injectable, PLATFORM_ID } from '#angular/core';
import { Observable, of } from 'rxjs';
import { StateKey, TransferState, makeStateKey } from '#angular/platform-browser';
import { isPlatformBrowser, isPlatformServer } from '#angular/common';
import { tap } from 'rxjs/operators';
#Injectable()
export class TransferStateInterceptor implements HttpInterceptor {
constructor(
private transferState: TransferState,
#Inject(PLATFORM_ID) private platformId: any,
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// For this demo application, we will only worry about State Transfer for get requests.
if (request.method !== 'GET') {
return next.handle(request);
}
// Use the request url as the key.
const stateKey: StateKey<string> = makeStateKey<string>(request.url);
// For any http requests made on the server, store the response in State Transfer.
if (isPlatformServer(this.platformId)) {
return next.handle(request).pipe(
tap((event: HttpResponse<any>) => {
this.transferState.set(stateKey, event.body);
})
);
}
// For any http requests made in the browser, first check State Transfer for a
// response corresponding to the request url.
if (isPlatformBrowser(this.platformId)) {
const transferStateResponse = this.transferState.get<any>(stateKey, null);
if (transferStateResponse) {
const response = new HttpResponse({ body: transferStateResponse, status: 200 });
// Remove the response from state transfer, so any future requests to
// the same url go to the network (this avoids us creating an
// implicit/unintentional caching mechanism).
this.transferState.remove(stateKey);
return of(response);
} else {
return next.handle(request);
}
}
}
}
If you want to add custom cache to this you can by installing memory-cache but I haven't tried that out yet. For more references these articles helped me out a lot and maybe they can help you too.
https://itnext.io/angular-universal-caching-transferstate-96eaaa386198
https://willtaylor.blog/angular-universal-for-angular-developers/
https://bcodes.io/blog/post/angular-universal-relative-to-absolute-http-interceptor
If you haven't you may need to add ServerTransferStateModule to your app.server.module file.
//app.server.module
import { NgModule } from '#angular/core';
import {
ServerModule,
ServerTransferStateModule
} from "#angular/platform-server";
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
#NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule
],
bootstrap: [AppComponent],
})
export class AppServerModule {}
good luck!
I was struggling with this error for days until I found this article About how to create a relative to absolute interceptor
here's the link
https://bcodes.io/blog/post/angular-universal-relative-to-absolute-http-interceptor
I created "universal-relative.interceptor.ts" file at my src folder
put this interceptor code in "universal-relative.interceptor.ts" file
import { HttpHandler, HttpInterceptor, HttpRequest } from '#angular/common/http';
import { Inject, Injectable, Optional } from '#angular/core';
import { REQUEST } from '#nguniversal/express-engine/tokens';
import { Request } from 'express';
// case insensitive check against config and value
const startsWithAny = (arr: string[] = []) => (value = '') => {
return arr.some(test => value.toLowerCase().startsWith(test.toLowerCase()));
};
// http, https, protocol relative
const isAbsoluteURL = startsWithAny(['http', '//']);
#Injectable()
export class UniversalRelativeInterceptor implements HttpInterceptor {
constructor(#Optional() #Inject(REQUEST) protected request: Request) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (this.request && !isAbsoluteURL(req.url)) {
const protocolHost = `${this.request.protocol}://${this.request.get(
'host'
)}`;
const pathSeparator = !req.url.startsWith('/') ? '/' : '';
const url = protocolHost + pathSeparator + req.url;
const serverRequest = req.clone({ url });
return next.handle(serverRequest);
} else {
return next.handle(req);
}
}
}
Go to your "app.server.module.ts" file
add your interceptor like this
import { NgModule } from '#angular/core';
import {
ServerModule,
ServerTransferStateModule,
} from "#angular/platform-server";
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { UniversalRelativeInterceptor } from 'src/universal-relative.interceptor';
import { HTTP_INTERCEPTORS } from '#angular/common/http';
#NgModule({
imports: [AppModule, ServerModule, ServerTransferStateModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UniversalRelativeInterceptor,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppServerModule {}
And the error was GONE!
For me simply the error was that my API variable was undefined, because of the Angular SSR life-cycle. The data was only available after the browser module loaded.
I was using something like
this.isBrowser$.subscribe(isBrowser => { ... });
to set the appropriate api endpoint.
As David replied in the original issue, in my case was the resourceUrl variable that I was using, was not absolute for production environment.
environment.ts
export const environment = {
resourceUrl: 'http://localhost:8082/api/site',
siteId: '1111'
};
Like you see, for development, I was using an absolute url "http://localhost:8082/api/site" for resourceUrl environment variable. Ofcourse this was working on development mode.
environment.prod.ts
export const environment = {
resourceUrl: '/api/site',
siteId: '1111'
};
In production mode I was using a relative url (/api/site), and this was causing the issue while running "serve:ssr" which is production.
return this.http.get<ISomething>(`${environment.resourceUrl}/home/${environment.siteId}`);
So I changed environment.prod.ts to use an absolute URL. Then the issue was gone.
I am adding this reply, since maybe someone doesnt look at David comment. Thanks David.
In case someone needs, if you are using ng-universal, and because the server side rendering caused the error, then you can simply use
if (typeof window === 'object') {
// your client side httpClient code
}

wordpress and angular theme update post list on when new post is published

Hi i'm new in Angular 4 and I want to use it to build a WordPress theme using the wp-api. I start with the ng-wp-theme but I and all its working fine, but I need that hen a new post is publish the post list page updates itself without reload the page. I saw some tutorials about the http services in angular but I dont find any solution to this, maybe its a Wordpress api issue and not the Angular part.
here is the service:
import { Injectable } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { Observable } from 'rxjs/Observable';
import { Post } from './post';
import { environment } from '../../environments/environment';
#Injectable()
export class PostsService {
private _wpBase = environment.wpBase;
constructor(private http: HttpClient) { }
getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + 'posts');
}
getPost(slug: string): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + `posts?slug=${slug}`);
}
}
and the controller:
import { Component, OnInit } from '#angular/core';
import { Post } from '../post';
import { PostsService } from '../posts.service';
import { Router } from '#angular/router';
import { HttpErrorResponse } from '#angular/common/http';
#Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css'],
providers: [PostsService]
})
export class PostListComponent implements OnInit {
public posts: Post[];
constructor( private postsService: PostsService, private router: Router ) {}
ngOnInit() {
this.postsService.getPosts().subscribe(
(posts: Post[]) => this.posts = posts,
(err: HttpErrorResponse) => err.error instanceof Error ? console.log('An error occurred:', err.error.message) : console.log(`Backend returned code ${err.status}, body was: ${err.error}`));
}
selectPost(slug) {
this.router.navigate([slug]);
}
}

Angular 2 : Access Cookie after Creation

I have two Component and one Service
Components:
1: LoginComponent
2: HeaderComponent (Shared)
Service:
1: authentication.service
In LoginComponent I use authentication.service to get authenticate and after successful authentication, I add User info into the Cookie and in the end, I automatically navigate to return-URL page, in the returned page I have a Component for the header that must show User info from the saved Cookie, BUT there is nothing in the cookie unless I refresh manually the page with F5 button.
My question is how can I access the cookie without refreshing the page?
Update
this is where I want to get the cookie:
import { Component, OnInit } from '#angular/core';
import { CookieHelper } from '../../_helpers/index';
#Component({
moduleId: module.id,
selector: 'app-header-ichart',
templateUrl: 'header.component.html',
styleUrls: ['header.component.css']
})
export class HeaderComponent implements OnInit {
currentUser = '';
isLogged = false;
constructor(private cookie: CookieHelper) { }
ngOnInit() {
this.isLogged = this.cookie.checkCookie('currentUser');
if (this.isLogged) {
this.currentUser = JSON.parse(this.cookie.getCookie('currentUser'));
}
}
}
Update 2
I used your suggestion technic to achieve my goal but need more help:
I Update my AuthenticationService to serve Observable Variable:
AuthenticationService:
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import { AppConfig } from '../app.config';
import { CookieHelper } from '../_helpers/index';
#Injectable()
export class AuthenticationService {
cookies: Object;
keys: Array<string>;
user$ = new Subject<any>();
constructor(private http: Http, private config: AppConfig, private cookie: CookieHelper) { }
login(username: string, password: string) {
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = `grant_type=${'password'}&username=${username}&password=${password}`;
return this.http.post(
this.config.apiUrl + '/token',
body, { headers: headers })
.map((response: Response) => {
// login successful if there's a jwt token in the response
let user = response.json();
if (user && user.access_token) {
user['username'] = username;
// Observable Variable
this.user$.next(JSON.stringify(user));
// store user details and jwt token in cookie to keep user logged in between page refreshes
this.cookie.addCookie('currentUser', JSON.stringify(user));
}
});
}
getUser(): Observable<any> {
return this.user$.asObservable();
}
logout() {
// remove user from cookie to log user out
this.cookie.removeCookie('currentUser');
// Logout Subscribe
this.user$.next(null);
}
}
HeaderComponent:
export class HeaderComponent implements OnInit {
currentUser = '';
isLogged = false;
constructor(private cookie: CookieHelper, private auth: AuthenticationService) { }
ngOnInit() {
// Get the currentUser from Observable Variable
this.auth.getUser().subscribe(currentUser => { this.currentUser = currentUser; });
console.log(this.currentUser);
this.isLogged = this.cookie.checkCookie('currentUser');
if (this.isLogged) {
this.currentUser = JSON.parse(this.cookie.getCookie('currentUser'));
}
}
}
I suggest to use an Observable to achieve that. So your headerComponent will be notified after the login.
Update your authentication.service so that you have something like
import { Subject } from 'rxjs/Subject';
export class AuthenticationService {
user$: Subject<any>;
login() {
// login stuff
this.user$.next('userDetails');
}
logout() {
this.user$.next(null);
}
}
and then from whatever component you want you can check for the user$ observable.
In template with
{{ (user$ | async)?.username }}
or in code with
user$.subscribe(user => console.log(user.username))

Categories