Modifying Angular 4 instance field in the code does not update the template as expected

One issue I am encountering is that changes in the instance variable in my component class are not automatically reflected in my template file unless I explicitly call ref.detectChanges

The method signInWithGoogle in my auth service is called from the component to sign in with Google

signInWithGoogle(): Observable<User> {
    const observable = Observable.fromPromise(
      this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
    ).concatMap(result => {
      const url = environment.apiEndpoint + '/rest-auth/social/google/';
      const request = { access_token: result.credential.accessToken };
      return this.login(url, request);
    });
    return observable;
  }

  private login(url, request): Observable<User> {
    return this.http
      .post<User>(
        url,
        request
      )
      .concatMap((user: User) => {
        localStorage.setItem(
          environment.constants.STORAGE_USER,
          JSON.stringify(user)
        );
        return Observable.of(user);
      });
  }

Below is a relevant code snippet from my component:

export class LoginComponent implements OnInit {
    errorMessage: string;
    request = new LoginRequest();

    googleSignIn($event) {
        $event.preventDefault();
        this.authService.signInWithGoogle().subscribe(
          (user: User) => {
            console.log('logged in');
          },
          err => {
            this.errorMessage = 'Problem while signing in with Google';
          }
        );
      }
}

This is how I am using the errorMessage variable from the component file in my template

<ngb-alert *ngIf="errorMessage" [dismissible]="false" type="danger">
      {{errorMessage}}
</ngb-alert>

Answer №1

Consider incorporating an observable:

// inside the component
errorMessage$ = new BehaviorSubject<string>(null);

handleSignIn($event) {
    $event.preventDefault();
    this.authService.signInWithGoogle().subscribe(
      (user: User) => {
        console.log('Successfully logged in');
      },
      err => {
        this.errorMessage$.next('Issue encountered while signing in with Google');
      }
    );
  }

Utilize the async pipe within your template:

<ngb-alert *ngIf="errorMessage$ | async as errorMessage" [dismissible]="false" type="danger">
    {{ errorMessage }}
</ngb-alert>

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

Is there a way to simultaneously call two APIs and then immediately call a third one using RXJS?

I am looking to optimize the process of making API calls by running two in parallel and then a third immediately after both have completed. I have successfully implemented parallel API calls using mergeMap and consecutive calls using concatMap, but now I w ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

What is the best way to link styleUrls to a CSS file located in a different directory?

I am trying to include the CSS file src/app/shared/layouts/admin/admin.component.css in my component located at src/app/admin/create-company/create-company.component.ts How can I properly reference this css file in the styleUrls of create-company.componen ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

Exploring Google Places with Angular 2, Typescript, and Ionic 2

Has anyone successfully transformed this code into TypeScript? var map; var infowindow; function initMap() { var pyrmont = {lat: -33.867, lng: 151.195}; map = new google.maps.Map(document.getElementById('map'), { center: py ...

Web-based API for authentication system using Ionic framework and token-based login

I am developing a photo-sharing app that requires a login system. However, when attempting to log in, an error occurs stating that the value is not found. I am able to retrieve the value in services but struggling to get the email and password in login.pag ...

The pipe in Angular 2.0.0 was not able to be located

Error: Issue: Template parse errors: The 'datefromiso' pipe is not recognized Custom Pipe: import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: 'datefromiso' }) export class DateFromISO implements P ...

Leveraging Global Variables for Validation in Angular (Angular 10)

I am currently creating a form in Angular 10 which involves the use of validators. Specifically, I have been utilizing the Validators.min() method within my form... Instead of manually inputting the value '100' in the Validators.min('100&ap ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

Having trouble parsing the ICU expression. Utilizing angular for internationalization

I need to convert an array of left-menu items into another language, and I am encountering an error in my code. Here is the snippet: left-menu.component.html <ng-container *ngFor="let m of menuItems; let last = last"> <a mat-list-it ...

What methods can be used to create a responsive height in iOS applications using WebView with Nativescript?

I am facing an issue with the WebView not dynamically loading height on iOS (it works on Android). My content is dynamic and can grow in height, so setting a fixed height won't work for me. Can anyone provide assistance? <CardView *ngFor="let itin ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...

The React context hooks are failing to update all references

In my project, I am working on setting up a modal with a custom close callback. To achieve this, I used a useState hook to store the method and execute it within an already defined function called closeModal(). However, I encountered an issue when attempt ...

What is the correct way to integrate a new component into my JHipster + Angular project while ensuring that the routerlink functions properly?

After creating a new application on JHipster, I wanted to add a FAQ page to my web portal. However, the default CRUD components generated by JHipster made it look more like an admin/user view table. I needed to make the FAQ page accessible to visitors with ...

Data string not being converted correctly to date format

Here is a table I am currently working with: ID DateColumn 1 3/7/2019 5:29:38 AM 2 3/8/2019 5:28:38 AM 3 3/7/2019 5:30:38 AM 4 3/7/2019 5:31:38 AM The date column in this table is being processed as a string when bound to the grid. To ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

Customizing form validation in React using Zod resolver for optional fields

I am currently working on creating a form using React-hook-form and zod resolver. My goal is to have all fields be optional, yet still required despite being marked as optional in the zod schema: const schema = z.object({ name: z.string().min(3).max(50 ...

The numerical value of zero in React Native TypeScript is being interpreted as NaN

When attempting to map an array in React Native (Android) and use its values or keys as data for return, I encountered an issue where the value 0 is read as NaN. This problem also arose when utilizing a typescript enum. The versions I am using are: typesc ...

Troubleshooting: Issue with Angular 2 FormArray

Hey there! I'm currently working on my Angular 2 Recipe app where I want to display multiple ingredient details. I am using a FormArray but encountered an error while debugging with the browser developer tools. The error displayed on the Console tab i ...

typescript what type of functionality do dynamic class methods provide

I'm currently working on building a class that creates dynamic methods during the constructor stage. While everything is functioning properly, I've encountered an issue with VS Code's auto suggestion not recognizing these dynamic methods. Ho ...