Angular 4:在 API 调用后更新模板变量 [英] Angular 4: Update template variable after API call

查看:22
本文介绍了Angular 4:在 API 调用后更新模板变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件指令,用于显示带有一些信息的 div.

此组件称为 SitesComponent,并包含在页面中.SitesComponent 的主要行为很好,除了这个:

  • 我有一个对后端的 API 调用,我返回了一些数据,后端调用执行得很好,我收到了信息,但变量未在模板上更新

这是我的代码:

import { Component } from '@angular/core';从 '../../myapi' 导入 { MyApi };@成分({选择器:站点组件小部件",templateUrl: './sites-component.html',styleUrls: ['./sites-component.scss'],})导出类 SitesComponent {数据:任何= [];构造函数(私有 API:MyApi}ngOnInit() {var _ = 这个this.api.company_sites(this.companyId).subscribe(响应=>{//this.data = response;this.data = [1,2,3];},错误 =>{console.log("错误")})}}}

我尝试使用收到的响应和静态数据更新变量 data.UI 永远不会随着 API 调用内部的变化而更新.

我使用的是 Angular http 客户端:

import { HttpClient } from "@angular/common/http";

但是也没有用

  • 我做错了什么?

我读到有关使用 observables 或 promises 的 API,我尝试了两种方法,但找不到解决方案......当我更新 .subscribe() 中的变量时,我的 UI 永远不会更新strong> 或 .then() 函数

我忘了添加我的 html,但目前只有 3 行:

**{{数据}}**

我的问题摘要:

如果我这样做,模板上的变量会更新

ngOnInit() {this.data = [1,2,3,4]}

但是当我这样做时,模板上的变量没有更新:

ngOnInit() {var _ = 这个this.api.company_sites(this.companyId).subscribe(响应=>{this.data = [1,2,3];})}}

最终编辑

在另一个问题中找到了一个解决方案,我试图关闭这个.

解决我的问题的问题是:

Angular 2 视图不会订阅变量更改后更新

3 个基本步骤:

//导入 ChangeDetectorRef从'@angular/core'导入{ChangeDetectorRef};//将 ChangeDetectorRef 添加到构造函数构造函数(私有 CD:ChangeDetectorRef){}//在订阅函数结束时调用 markForCheckthis.cd.markForCheck();

我的代码结束如下:

import { Component } from '@angular/core';从 '../../myapi' 导入 { MyApi };//1从'@angular/core'导入{ChangeDetectorRef};@成分({选择器:站点组件小部件",templateUrl: './sites-component.html',styleUrls: ['./sites-component.scss'],})导出类 SitesComponent {数据:任何= [];构造函数(私有 API:MyApi,//2私人光盘:ChangeDetectorRef}ngOnInit() {var _ = 这个this.api.company_sites(this.companyId).subscribe(响应=>{this.data = 响应;//3this.cd.markForCheck()},错误 =>{console.log("错误")})}}}

解决方案

implement OnInit

import { OnInit } from '@angular/core';导出类 SitesComponent 实现 OnInit {}

I have a Component-directive that I use to show a div with some information.

This component is called SitesComponent and is included in a page. The main behavior of the SitesComponent is fine, except for this:

  • I have an API call to a backend where I return some data, the backend call is executed well and I received the information but the variable is not updated on the template

This is my code:

import { Component } from '@angular/core';
import { MyApi } from '../../myapi';

@Component({
  selector: 'sites-component-widget',
  templateUrl: './sites-component.html',
  styleUrls: ['./sites-component.scss'],
})
export class SitesComponent {
    data: any = [];
    constructor(private api: MyApi}

    ngOnInit() {
        var _ = this
          this.api.company_sites(this.companyId).subscribe(
            response => {
                //this.data = response; 
                this.data = [1,2,3]; 
            },
            error => {
              console.log("error")
            }
          )
        }        
    }
}

I tried to update the variable data using the received response and also using static data. The UI is never updated with the changes inside the API call.

I'm using angular http client:

import { HttpClient } from "@angular/common/http";

But it didn't work neither

  • What I'm doing wrong ?

I read about using observables or promises for the API, I tried both ways and I couldn't find a solution... My UI is never updated when I update the variable inside the .subscribe() or .then() functions

EDIT: I forgot to add my html, but as far it is just 3 lines:

<div class="sites-online-widget">
    **{{data}}**
</div>

Summary of my issue:

If I do this the variable is updated on the template

ngOnInit() {
    this.data = [1,2,3,4]
}

but when I do this, the variable is not updated on the template:

ngOnInit() {
    var _ = this
      this.api.company_sites(this.companyId).subscribe(
        response => {
            this.data = [1,2,3]; 
        }
      )}        
}

Final Edit

Found a solution that worked in another question, I tried to close this one.

The question that solved my issue was this:

Angular 2 View will not update after variable change in subscribe

3 basic steps:

// Import ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core';

// Add ChangeDetectorRef to constructor
constructor(private cd: ChangeDetectorRef) {}

// Call markForCheck at the end of the subscribe function
this.cd.markForCheck();

My code ended like:

import { Component } from '@angular/core';
import { MyApi } from '../../myapi';

// 1
import { ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'sites-component-widget',
  templateUrl: './sites-component.html',
  styleUrls: ['./sites-component.scss'],
})
export class SitesComponent {
    data: any = [];
    constructor(
      private api: MyApi,
      // 2
      private cd: ChangeDetectorRef}

    ngOnInit() {
        var _ = this
          this.api.company_sites(this.companyId).subscribe(
            response => {
                this.data = response; 
                // 3
                this.cd.markForCheck()
            },
            error => {
              console.log("error")
            }
          )
        }        
    }
}

解决方案

implement OnInit

import { OnInit } from '@angular/core';

export class SitesComponent implements OnInit {}

这篇关于Angular 4:在 API 调用后更新模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆