triggering observer.next() when a property changes

A login-logout application is currently being developed, with a navbar component that needs to update its view template based on the user's login status. The UserService service class contains a logout method. Here is a snippet of the Navbar component:

export class NavbarComponent implements OnInit {
  loginStatus: boolean;
  constructor(private _userService: UserService) { }

  ngOnInit() {
    this._userService.loginStatus().subscribe((data)=>{
      this.loginStatus = data;
      console.log('You are logged in:'+this.loginStatus)
    })
    setTimeout(()=>{
      this._userService.logout();
    }, 10000)// example usage for calling logout
  }

}

The UserService code snippet:

@Injectable()
export class UserService {
    private _token: string = null;

    set token(token) {
        localStorage.setItem('token', token);
        this._token = token;
        this.loggedIn = true;
    }
    get token() {
        if (this._token) {
            return this._token;
        }
        return this._token = localStorage.getItem('token');
    }
    private loggedIn: boolean = true;
    constructor(private _httpClient: HttpClient) { }

    logout(){
        console.log('out')
        this._token = null;
        this.loggedIn = false;
        localStorage.removeItem('token');
        localStorage.clear();
    }
    loginStatus(): Observable<boolean>{
        let observable: Observable<boolean> =  new Observable((observer) => {
            observer.next(this.loggedIn);
        })
        return observable;
    }
}

The loginStatus() method returns an observable subscribed in the Navbar component. An issue arises when logging out using the logout method - I need the loginStatus() method to emit data again. How can changes be detected in the loggedIn property to make the observable emit data? Any suggestions or alternative solutions would be greatly appreciated. Thank you.

Answer №1

Do you ever wonder why a Subject is not being utilized?

declare private loginStatus: Subject<boolean> = new Subject<boolean>();

(if needed, it can be made private with its own getter...). By subscribing to it similar to an observable, the following code should be executed:

loginStatus.next(this.loggedIn);

whenever there is a change in the login status.

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

InitAuth0 Auth0 encountering deepPartial error in Next.js with TypeScript setup

Having some trouble setting up auth0 with nextjs using typescript. When I try to initialize Auth0, I encounter an error regarding deep partials, Argument of type '{ clientId: string; clientSecret: string; scope: string; domain: string; redirectUri: st ...

A guide on selecting checkboxes using TypeScript by iterating through two arrays

These are my two arrays: let allItems = ["apple", "banana", "cherry", "date"]; let selectedItems = ["apple", "date"]; The existing code is as follows: let allItems = ["apple", "banana", "cherry", "date"]; let selectedItems = ["apple", "date"]; isItemSe ...

Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query: Excuse me, I am new to Typescipt & RxJS. I have this JSON data: [ { "ID": "", "UEN": "", "Name": "", "Address": "", "Telephone&quo ...

Discovering the data type from its textual representation

Is it possible for TypeScript to automatically determine the generic argument of assertTypeof based on the value of expectedType? I am looking for a way to use the function below without having to specify number multiple times. playable example type Typ ...

The React TypeScript MUI Autocomplete is giving an error: "Type 'Product[]' cannot be assigned to type 'readonly never[][]"

Having trouble with a ReactJS useEffect hook in an Autocomplete field while using Typescript version 4.9.5. The VS code editor is flagging an error on the line options={products}. Any assistance on resolving this issue would be greatly appreciated. You c ...

Guide to correctly importing a class definition from a module in TypeScript

Having trouble integrating the AsyncAPI Generator into my typescript project. The generator, being a commonjs module, is causing some complications. import { Generator } from '@asyncapi/generator'; const generator = new Generator('@asyncapi ...

Having trouble with ngx-pagination's next page button not responding when clicked?

I am experiencing issues with pagination. The next page button does not function as expected, and clicking on the page number also does not work. Below is the code snippet and a Demo link for your reference. HTML <table mat-table [dataSou ...

Issue: NG05105 - Unforeseen artificial listener detected @transform.start

Encountered an issue in my Angular 17 app using Angular Material during the execution of ng test: Chrome browser throws 'app-test' title error in the AppComponent with the following message: Error: NG05105: Unexpected synthetic listener @ ...

When attempting to display the image file path using the JavaScript API Notification in Angular, there is a challenge in

Hello fellow developers, I am currently facing an issue with retrieving a local image from my assets folder and displaying it on a new Notification object generated by the Web Notification API. I have an image in my assets folder with a .jpeg extension. ...

What are some ways to leverage the window object within Angular 2?

I attempted to include the following code in order to access a window object in angular 2: @Component({ selector: 'app-slider', templateUrl: './slider.component.html', styleUrls: ['./slider.compo ...

Ways of invoking a component method from a service in Angular 2

I have a concept for creating a unique service that is capable of interacting with one specific component. In my application, all other components should have the ability to call upon this service and then have it interact with the designated component in ...

Issues with Angular 4 Rxjs subject subscription functionality

My application consists of a shared service named data.service.ts, which contains the following code: public pauseProjectTask$: Subject<any> = new Subject<any>(); pauseTaskProject(taskData, type){ this.pauseProjectTask$.next(taskData); ...

Customize the default styles for Angular 2/4 Material's "md-menu" component

Seeking to customize default styles of md-menu in Angular Material. The challenge lies in the dynamic generation of elements by Angular Material, preventing direct access from HTML. Visual representation of DOM: https://i.sstatic.net/v8GE0.png Component ...

What is the mechanism behind Angular 2's ability to locate the source of imported items?

While reviewing the Angular 2 Quickstart, I came across a peculiar discovery. The angular files contained these lines at the top: import {bootstrap} from 'angular2/platform/browser'; import {AppComponent} from './app.component'; T ...

Creating an array using an enumeration

I've been facing challenges trying to pinpoint the root cause of the issue with this code. It would be greatly appreciated if someone could shed light on what is triggering the problem and possibly suggest a solution. Within my application, I am atte ...

What is the rationale behind ngOnInit not being a private method in Angular?

After extensively checking both code samples and even the official documentation, I am still unable to find the information I need. Turning to Google has also yielded no results. The question that baffles me is: ngOnInit() { ... } Why do we use this syn ...

What is the proper method for implementing an event listener exclusively for a left mouse click?

Is there a way to make Phaser recognize only left mouse clicks as click events, excluding right and middle clicks? Check out this Phaser example at the following link: https://phaser.io/examples/v2/basics/02-click-on-an-image. ...

Encountering errors while working with React props in typing

In my application, I am utilizing ANT Design and React with 2 components in the mix: //PARENT const Test = () => { const [state, setState] = useState([]); function onChange( pagination: TablePaginationConfig, filters: Record<string, ...

Bypassing disputes in a TypeScript function

I attempted to implement the solution provided by Pacerier in response to the question about skipping arguments in a JavaScript function. However, it doesn't seem to be working for me. The function I am dealing with has numerous arguments. this.servi ...

What are the steps for incorporating TypeScript into a project created with Vue CLI@3?

td;dr How can I integrate vue-apollo into an existing TypeScript project? I initialized a new Vue project using vue cli@3 with TypeScript. Afterwards, I installed the vue-apollo plugin which automatically updated my main.ts file to include apolloProvide ...