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

Eliminate the hashtag (#) from the URL in Angular 11

I am facing an issue with removing the # from the URL. When I try to remove it, the application encounters a problem upon deployment to the server. Upon page refresh, a 404 error status is returned. For instance: https://example.com/user/1 (works) https ...

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is exec ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

Before running any unit tests, I have to address all linting issues as required by ng test

Upon running ng test, the output I receive is as follows: > ng test 24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/ 24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ ...

Changes to the value of an Angular FormControl will automatically trigger changes in the entire formgroup

When attempting to validate the uniqueness of a user's email through an API call, I encountered a problem where any changes in form controls would trigger the value change. Below is my code: Errors(){ this.form01.valueChanges .subscribe((changed ...

Is there a way to use Jest spyOn to monitor a function that is returned by another function?

I'm curious about why the final assertion (expect(msgSpy).toBeCalled()) in this code snippet is failing. What adjustments should be made to ensure it passes? it('spyOn test', () => { const newClient = () => { const getMsg = ...

Angular List Selector: A versatile multiple selection component with a stylish list design

I'm in need of a select component similar to the one shown in The issue is that Material Angular doesn't have this specific component, so I opted to use the default HTML select inside my component. Everything was working fine until I tried to de ...

Effortless Route Loading in React Using Typescript's AsyncComponent for Dynamic Loading

I have been experimenting with lazy loading routes in React by following the example provided in the documentation for implementing the AsyncComponent class. The tutorial I referenced can be found here. Below is the asyncComponent function written in ES6 f ...

Having trouble manipulating text or values of angular elements with Selenium and Python

https://i.stack.imgur.com/vZdo0.png I am facing an issue with a date input field that does not have a calendar or dropdown for selection. I tried using driver.find_element_by_id('dataInicio').send_keys(date_value) but it doesn't seem to work ...

implementing firestore onsnapshotListner feature with pagination

I have a web application that needs real-time updates on a large collection of documents. However, due to the size of the collection, retrieving data without applying a limit is not feasible and inefficient. Therefore, it is crucial to implement a query li ...

Combine the information from 3 separate subscriptions into a single object using RxJS in Angular 9

I am seeking assistance with merging data from 3 different sensors into one object. I am using Cordova plugins to retrieve accelerometer, gyroscope, and magnetometer data. However, I am facing an issue in subscribing to all three observables simultaneously ...

Enhance your Angular material datepicker with additional content such as a close button

I'm currently working on customizing my Angular Material datepicker by adding a button. The goal is to have this button placed in the top right corner and enable it to close the datepicker when clicked. In addition, I also want to include extra conte ...

Concealing elements in Angular 2

My intention was to conceal the components, so that when he came back later everything would be just as it was before. The only issue is that I am unsure of how to achieve this. Does anyone have any examples or know of a similar method that could help me ...

Discover the steps to include the property within the data model in Angular specifically meant for showcasing on the user interface list page

class UserIdentity { public uniqueID: string; public fullName: string; public bio: string; public service: string; public groupID: string; public userID: string; public secretKey: string; constructor(details?: any) { this.uniqueID = &a ...

Use Typescript to access and utilize the value stored in local storage by using the

Trying to retrieve the language setting from localHost and implement it in a translation pipe as shown below: transform(value: string): string {... localStorage.setItem("language", JSON.stringify("en")); let language = JSON.parse(loca ...

Infinite Loop Issue in Angular2 RC5 when using the templateUrl

Encountering an issue with Angular2 RC5 that seems to be causing an infinite loop problem. The app.component, which is bootstrapped by the app.module, appears quite simple: @Component({ selector: 'my-app', template: `TEST` }) export cl ...

Moving SVG Module

My goal is to create a custom component that can dynamically load and display the content of an SVG file in its template. So far, I have attempted the following approach: icon.component.ts ... @Component({ selector: 'app-icon', templa ...

Vitek - Uncaught ReferenceError: Document Is Not Defined

Why am I encountering an error when trying to use File in my vitest code, even though I can typically use it anywhere else? How can I fix this issue? This is the content of my vite.config.ts. /// <reference types="vitest" /> import { defin ...

Angular Back button event not triggering

I'm attempting to redirect the user to a specific URL when they click the back button in their browser. Here is the code snippet: constructor(private router: Router,private location: PlatformLocation) { let eventUrl = window.sessionSt ...