AngularJS 2: Updating variable in parent component using Router

My current app.component looks like the following:

import { Component, Input } from '@angular/core';

import {AuthTokenService} from './auth-token.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    constructor(
        private Auth: AuthTokenService) { };

    isGuest: any = this.Auth.canActivate();
    title = 'app works!';
}

I want to update the isGuest variable from the child component login.component.

In my app.component.html, I have the following code:

<h1>
    {{isGuest}}
</h1>
<router-outlet></router-outlet>

I attempted to modify it using @Output and Emitter, but it didn't work due to angular router being used.

Answer №1

In my opinion, I suggest implementing the Observable pattern in the auth service, similar to what is explained in the Angular documentation (https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service).

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
@Injectable()
export class AuthService {
  /* ... */
  private authStatus = new Subject<string>();
  public authStatus$ = this.authStatus.asObservable();
  /* ... */
  authenticate() {
    /* ... */
    if (authenticated) {
      this.authStatus.next(true);
    } else {
      this.authStatus.next(false);
    }
    /* ... */
  }
  /* ... */
}

Subscribing in your app.component can be done like this:

this.Auth.authStatus$.subscribe(authenticated => {
  /* handle authentication status changes here */
});

To display in your template using the async pipe:

{{ Auth.authStatus$ | async }}

For more information about the Async Pipe, you can visit: https://angular.io/docs/ts/latest/api/common/index/AsyncPipe-pipe.html

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

Initiate the function one time

The Introduction: I need assistance with a form that triggers a jQuery function when a button is clicked. The issue arises after the initial execution, as the function continues to run one more time. My dilemma is figuring out how to ensure that the funct ...

There is no value inputted into the file

I'm facing a small issue while trying to retrieve the value from my input of type="file". Here is the code snippet: <tr ng-repeat="imagenDatos in tableImagenesPunto | filter: busquedaDatosPunto " > <td>PNG</td> <td>{{imag ...

Avoid reloading the page when submitting a form using @using Html.BeginForm in ASP.NET MVC

I have a webpage featuring a model that needs to be sent to the controller along with additional files that are not part of the model. I have been able to successfully submit everything, but since this is being done in a partial view, I would like to send ...

Is it possible for an angular directive to transmit arguments to functions within specified expressions in the directive's attributes?

I am working on a form directive that utilizes a specific callback attribute with an isolate scope: scope: { callback: '&' } This directive is placed within an ng-repeat, where the expression passed in includes the id of the object as an ar ...

Implement Material UI Card Component in your React Project

I'm currently working on a project that includes a page with expandable cards arranged in a list format. The code I have right now is not very scalable, as I keep adding individual card tags for each item. What I would like to achieve is to load data ...

AsExpression Removes Undefined from Type More Swiftly Than I Prefer

Utilizing an API that returns a base type, I employ the as keyword to convert the type into a union consisting of two sub-types of the original base type. interface base { a: number; } interface sub1 extends base { s1: number; } interface sub2 extends bas ...

Removing duplicate entries from a dropdown menu can be achieved by implementing

As a newcomer to the world of PHP PDO, I've learned that the database connection should be in a separate PHP file. However, after spending an entire day trying different things, I'm still facing issues. I suspect that the duplicate entries are a ...

Error code E11000 is indicating that a duplicate key issue has occurred in the collection "blog-api.blogs" where the index "id_1" is

Issue with Error E11000 duplicate key error collection: blog-api.blogs index: id_1 dup key: { id: null } Encountering an error when trying to insert data after initially inserting one successfully. Referencing the blogSchema.js: const mongoose = req ...

The process of retrieving data from Firebase Firestore

Here is the content of my HTML File: <div class="container m-3 p-3"> <h1>Current Items</h1> <ul class="list-group"> <li class="list-group-item">An item</li> <li class="list-gro ...

I'm curious about the meaning of "!" in pseudo-code. I understand that it represents factorial, but I'm unsure of how to properly interpret it

Can someone explain the meaning of ! in pseudo-code to me? I understand that it represents factorial, but for some reason I am having trouble translating it. For example: I came across this code snippet: if (operation!= ’B’ OR operation != ’D’ O ...

What is the best way to test a try/catch block within a useEffect hook?

Hey, I'm currently dealing with the following code snippet: useEffect(() => { try { if (prop1 && prop2) { callThisFunction() } else { callThatFunction() } ...

Failure when running npm start command in Nest js

After setting up a fresh Nest js on a new EC2 machine, I encountered an error when trying to run it for the first time. The error message indicated that the npm install process failed abruptly without any visible error: ubuntu@ip-172-31-15-190:~/projects/m ...

JavaScript preloader function isn't functioning properly when paired with a button

I'm currently working on developing a preliminary landing page for my game using JavaScript. I have integrated a class that overlays my main content, and added an 'onclick' function named fadeOut() for my button in JavaScript. However, the f ...

Leveraging the power of Firebase and JavaScript to easily include custom user fields during the user

UPDATE: I encountered an issue while using Nextjs framework. However, it works perfectly fine when I use a vanilla CRA (Create React App). It appears that the problem is somehow related to Nextjs. I'm currently working on creating a new user document ...

What is the best method for automatically closing the modal window?

I implemented a modal window on my website. Within the modal, there is a green button labeled "Visit" which triggers the "Bootstrap Tour". I aim for the modal to automatically close when the tour starts. To access this feature on my site, users need to ...

Resizing a webpage to fit within an IFRAME

Having just started learning HTML, CSS, and JavaScript, I am attempting to incorporate a page as a submenu item on my website. Below is the code that I have so far: <!DOCTYPE html> <html> <meta name="viewport" content="width=1024"> ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

One click wonder: Easily print any webpage content with just the click of a button!

For example, upon clicking the button on my webpage, I want the content of another page to be sent directly to a printer. The objective is to bypass the print dialog box and print preview that typically appears when using the browser's default printin ...

Tips for updating grid variables in Bootstrap 4 and Angular

What's the best way to truly override bootstrap variables? I've tried the following code but it's not working // overrides.scss @import '~bootstrap/scss/functions'; @import '~bootstrap/scss/variables'; @import '~boo ...