Angular 6:调用Subscribe方法时不会更新视图

时间:2018-06-14 09:34:35

标签: angular typescript

这个问题是基于这个问题(提供的解决方案没有工作): Angular 4: Update template variable after API call [duplicate]

我在使用HttpClient进行api调用后更新视图,但我的html模板没有更新。

product.ts

export class ProductModel {
ID:number;
Name:String;
CategoryName:String;
Price:number;
OldPrice:number;
IsNew:Boolean;
InStock:Boolean;
Image:String;

}

products.service.ts

import { Component, Injectable, Injector } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { HttpClient, HttpParams, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';

import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map} from 'rxjs/operators';

import { ProductModel } from 'src/app/models/product';

@Injectable()
export class ProductsService { 

  constructor(private http: HttpClient) { } 

  GetProducts(): Observable<ProductModel[]>{      
      return this.http.get<ProductModel[]>('https://myapi.com/api/products');
    } 
}

products.component.ts

import { Component, OnInit, ViewEncapsulation, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatSidenav } from '@angular/material/sidenav';
import {MatExpansionModule} from '@angular/material/expansion';

import {Observable} from 'rxjs';
import { map } from 'rxjs/operators';

import * as $ from 'jquery';

import {ProductsService} from '../../services/products.service';

import { ProductModel } from 'src/app/models/product';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
  providers: [ProductsService],
  encapsulation: ViewEncapsulation.None 
})
export class ProductsComponent implements OnInit { 
  @ViewChild('sidenav') sidenav: MatSidenav;

  public productsList = [];
  private reason:string;

  constructor(private _productsService: ProductsService, 
    private _ref: ChangeDetectorRef) {  
  }

  ngOnInit(){ 
    this.GetProducts();  
    console.log(this.productsList);
  } 

  close(reason: string) {
    this.reason = reason;
    this.sidenav.close();
  }

  GetProducts(){  
    this._productsService.GetProducts()
    .subscribe(
      response => {
        this.productsList = response; 
        this._ref.markForCheck();
        console.log(this.productsList);
      },
      error => { console.log(error) }
    );  
  }  

}

products.component.html

 <ul>
  <li *ngFor="let prod of productsList" >
    Id: {{prod.ID}} <br>
    Name: {{prod.Name}} <br>
    CategoryName: {{prod.CategoryName}} <br>
    Price: {{prod.Price}} <br>
    OldPrice: {{prod.OldPrice}} <br>
    IsNew: {{prod.IsNew}} <br>
    InStock: {{prod.InStock}} <br>
    Image: {{prod.Image}} <br>
  </li>
</ul>

的package.json

{
  "name": "smak",
  "version": "0.0.0",
  "scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},
"private": true,
"dependencies": {
  "@agm/core": "^1.0.0-beta.3",
  "@angular/animations": "^6.0.4",
  "@angular/cdk": "^6.1.0",
  "@angular/common": "^6.0.4",
  "@angular/compiler": "^6.0.4",
  "@angular/core": "^6.0.4",
  "@angular/forms": "^6.0.4",
  "@angular/http": "^6.0.4",
  "@angular/material": "^6.1.0",
  "@angular/platform-browser": "^6.0.4",
  "@angular/platform-browser-dynamic": "^6.0.4",
  "@angular/router": "^6.0.4",
  "core-js": "^2.5.4",
  "hammerjs": "^2.0.8",
  "jquery": "^3.3.1",
  "rxjs": "^6.2.1",
  "zone.js": "^0.8.26"
},
  "devDependencies": {
  "@angular-devkit/build-angular": "~0.6.3",
  "@angular/cli": "~6.0.3",
  "@angular/compiler-cli": "^6.0.4",
  "@angular/language-service": "^6.0.4",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/jquery": "^3.3.2",
  "@types/node": "~8.9.4",
  "codelyzer": "~4.2.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~1.4.2",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1",
  "typescript": "~2.7.2"
}
}

请参阅我的console.log view console log

如果你看到我的控制台日志,我的变量受到影响(内部订阅),但外部订阅我的变量是空的。

有没有人有同样的问题? 我怎么解决?这是一个错误吗?

最诚挚的问候,

3 个答案:

答案 0 :(得分:1)

@LuisFerreira,我必须支持你收到一些喜欢的 [{分类: “Cereails”,产品:[{ID:1,名称: “特里戈”,...},{ID:2,名称: “马伊斯”,...}]

所以你必须做两个* ngFor

<ul *ngFor="let item of productList">
  <!--item is, e.g. {Category:"Cereails",Products:[{Id:1,Name:"Trigo",...} --> 
  <li *ngFor="let prod of item.Products" >
    <!-- prod is,e.g. {Id:1,Name:"Trigo",...} -->
    Id: {{prod.ID}} <br>
    Name: {{prod.Name}} <br>
    CategoryName: {{item.Category}} <br> <!--see that I use item.Category here -->
    Price: {{prod.Price}} <br>
    OldPrice: {{prod.OldPrice}} <br>
    IsNew: {{prod.IsNew}} <br>
    InStock: {{prod.InStock}} <br>
    Image: {{prod.Image}} <br>
  </li>
</ul>

忘记ChangeDetectorRef或ngZone

答案 1 :(得分:0)

我有同样的问题,它在检索到响应时使用这行代码解决了。

    this.changeDetector.detectChanges();

在你的情况下,getProducts应该是这样的:

GetProducts(){  
    this._productsService.GetProducts()
    .subscribe(
      response => {
        this.productsList = response; 
        this._ref.detectChanges();
        console.log(this.productsList);
      },
      error => { console.log(error) }
    );  
  }  

另一种解决方案:

检测到更改时可能是区域冲突

将NgZone添加到构造函数

constructor( 
          ...
             private zone:NgZone 
          ...
           ) {}

然后你的方法应该是这样的:

GetProducts(){  
    this._productsService.GetProducts()
    .subscribe(
      response => {
        this.zone.run(() => { // <== execute the changes in this callback.
            this.productsList = response; 
            console.log(this.productsList);
        });
      },
      error => { console.log(error) }
    );  
  }  

答案 2 :(得分:0)

如果您只关心Products数组中的项目,则只需选择并展平*ngFor数组即可绕过必须使用两个Products循环。

GetProducts() {  
    this._productsService.GetProducts().subscribe(response => {
        // Essentially the same as a SelectMany() in linq
        this.productsList = [].concat.apply([], response.map(p => p.Products)); 
    }, error => { console.log(error) });  
}

这会使您的productsList数组中的每个元素都是单个产品。现在,您可以访问产品的所有属性,并且模板中只有一个/ *ngFor列表!