Angular 6's subscribe method is causing the UI to not update

I'm currently facing an issue where my component does not refresh the UI after I input data. I always have to manually refresh the page to see the changes. I suspect there might be a problem with the .subscribe method in Angular 6. Previously, when I was using a pure Angular 2 environment, it worked fine.

Below is my component:

ngOnInit() {
    this.company = [];
    this.inputCompanyService.getAllCompany().subscribe(company => {
      this.company = company;
    });
  }


postCompany(event, companyName, ) {
    var result;
    var newCompany = {
      company_name: companyName.value,
      id: companyName.id
    };
    result = this.inputCompanyService.postCompany(newCompany);
    result.subscribe(x => {
      this.company.push(newCompany);
      companyName.value = '';
    });

  }

This is my service:

getAllCompany() {
            return this._http.get('http://localhost:3000/api/companys')
                  .map(res => res.json());
      }

postCompany(company_name) {
            var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            return this._http.post('http://localhost:3000/api/company', JSON.stringify(company_name), { headers: headers })
                  .map(res => res.json());
      }

Here's the HTML code:

<div class="input-company">
  <p>
    <mat-form-field appearance="legacy">
      <input matInput [(ngModel)]="companyName.company_name" placeholder="Here..." autofocus #companyName>
      <!-- <mat-icon matSuffix>sentiment_very_satisfied</mat-icon> -->
    </mat-form-field>
    <button mat-raised-button color="warn" (click)="postCompany($event, companyName)">Click me !</button>
  </p>
  <div *ngFor="let company of company.company">
    <li>
    <button mat-flat-button (click)="deleteCompany(company)">X</button>
    <button mat-flat-button>N</button>
    <button mat-stroked-button>{{company.id}}-{{company.company_name}}</button>
  </li>    
  </div>
</div>

Answer №1

The asynchronous call is occurring outside of the Angular Zone.

An easy solution:

// Update variables and trigger Angular to check them inside the subscribe block
this._ngZone.run(() => {
    this.company.push(newCompany);
    companyName.value = '';
});

If desired, you can refactor slightly to utilize the AsyncPipe:

this.companies$: Observable<any>;
ngOnInit() {
    this.companies$ = this.inputCompanyService.getAllCompany();
}

and in the template...

<div class="input-company">
  <p>
    <mat-form-field appearance="legacy">
      <input matInput [(ngModel)]="companyName.company_name" placeholder="Here..." autofocus #companyName>
      <!-- <mat-icon matSuffix>sentiment_very_satisfied</mat-icon> -->
    </mat-form-field>
    <button mat-raised-button color="warn" (click)="postCompany($event, companyName)">Click me!</button>
  </p>
  <ng-container *ngIf="(companies$ | async) as companies)"
    <div *ngFor="let company of companies.company">
      <li>
       <button mat-flat-button (click)="deleteCompany(company)">X</button>
       <button mat-flat-button>N</button>
       <button mat-stroked-button>{{company.id}}-{{company.company_name}}</button>
     </li>    
    </div>
  <ng-container>
</div>

Best of luck!

Answer №2

Retrieve companies and save them into an array.

this.company = [];
this.inputCompanyService.getAllCompany().subscribe(company => {
      this.company = company;
});

However, the iteration in the template is using company.company:

<div *ngFor="let company of company.company">

It should be:

 <div *ngFor="let c of company">
   <li>
    <button mat-flat-button (click)="deleteCompany(c)">X</button>
    <button mat-flat-button>N</button>
    <button mat-stroked-button>{{c.id}}-{{c.company_name}}</button>
  </li>    
 </div>

Variable name has been changed to c for clarity purposes. It is also recommended to rename the array as companies for better understanding.

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

Angular MSAL Azure AD Dotnet Core Web API facing Cross-Origin Resource Sharing (CORS) challenge

I've been following along with this tutorial: https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi The authentication is working correctly. However, I'm encountering a CORS exception in the console: Cross-Orig ...

Ensure that all files with the extension ".ts" take precedence and are imported

I am facing an issue with my component as I have two files associated with it: app/components/SomeButton.ts app/components/SomeButton.tsx The .ts file contains most of the logic and code, while the .tsx file extends the .ts and only contains the ren ...

Generating auto UUIDs in PostgreSQL using TypeORM

Currently, I am in the process of developing a REST API and utilizing TypeORM for data access. While I have been able to use it successfully so far, I am facing an issue regarding setting up a UUID auto-generated primary key on one of my tables. If anyone ...

Angular2: Continuous User Authentication Guard

I am in the process of developing an application that requires strict authentication for all users. To enforce this, I have created a LoggedInGuard. However, I find myself having to include canActivate: [LoggedInGuard] in every route definition within my ...

After utilizing the nativescript command "tns create my-tab-ng --template tns-template-tab-navigation-ng," there was no webpack.config.js file generated

Whenever I attempt to execute the command tns run android while my device is connected to my computer, an error message pops up stating that the webpack.config.js file cannot be located. I initialized the project using the command tns create my-tab-ng -- ...

Performing a series of HTTP requests within a single @ngrx/effect

I need some guidance as I am new to @ngrx and feeling a bit lost in understanding how it should be used. Let's assume we have an effect named PlaceOrderEffect In this effect, my goal is to handle each request in a specific order. processOrder$ = cre ...

Angular 8: Setting the Default Dropdown Option to the Newest Value in the Updated ArrayList

I am currently working with Angular 8 and TypeScript. After calling a service and updating the array collection, I want to automatically select the last aggregated value. However, I always want the placeholder to be shown. How can I achieve this? <nb- ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

What are the steps to resolve the UglifyJs error stating 'Unexpected token operator'?

When running the following command in my Angular app: > ng build --prod --aot --env=staging I encounter this error message: ERROR in vendor.0625f773941bc83e6748.bundle.js from UglifyJs Unexpected token operator «*», expected punc «(» [vendor.0625 ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

How can we prevent Express static from serving the index.html file?

Encountering an issue when serving my angular 5 app from node express, where express static serves index.html for domain.com, but works correctly for domain.com/something. Can anyone help me figure out how to solve this? app.use(express.static(path.join(_ ...

How can TypeScript objects be serialized?

Is there a reliable method for preserving type information during JSON serialization/deserialization of Typescript objects? The straightforward JSON.parse(JSON.stringify) approach has proven to have several limitations. Are there more effective ad-hoc sol ...

Having trouble resolving all parameters for the SiteNotificationComponent: (?)

I encountered an issue while attempting to append a component to the DOM. The error message displayed was "Can't resolve all parameters for SiteNotificationComponent: (?).at syntaxError." My goal was to insert HTML content by invoking showNotificatio ...

Send information to the main application component

Can data be passed two or more levels up from a Child Component to the App Component? https://i.stack.imgur.com/JMCBR.png ...

Incorporating PrimeNG into your Bootstrap 4 projects

Exploring various UI libraries for a new Angular 2 project has been an interesting journey. From Ng-Bootstrap and Material to PrimeNG, each library has its own strengths and weaknesses. Currently, I find that PrimeNG offers a wider range of components comp ...

Troubleshoot: Angular5 Service call not functioning properly when called in ngOnInit

Every time I go to the results component, the service inside ngOnInit behaves as expected. However, when I open the side menu, navigate to another page, and then return to the results page, the page fails to render the results. Instead, the ng-template is ...

Setting up the viewport addon in Angular can be done by following these steps

After checking this documentation, I attempted to add a custom viewport in the config.js file: import { setParameters } from '@storybook/angular'; // switching from react to angular import { INITIAL_VIEWPORTS } from '@storybook/addon-viewpo ...

Consolidating Typescript modules into a single .js file

Recently, I was able to get my hands on a TypeScript library that I found on GitHub. As I started exploring it, I noticed that there were quite a few dependencies on other npm packages. This got me thinking - is there a way to compile all these files int ...

Angular 4 animations failing to run on Safari iOS 9.3

In my current app testing phase, I noticed that the angular animations are not functioning as expected in Safari iOS 9.3. Despite spending hours trying to troubleshoot the issue, I still couldn't resolve it on my own. Therefore, I am seeking assistanc ...