gpt4 book ai didi

Angular 6 : View is not updated when Subscribe method is called

转载 作者:行者123 更新时间:2023-12-02 03:34:05 27 4
gpt4 key购买 nike

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

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

产品.ts

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

}

产品.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

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

有人遇到同样的问题吗?我该如何解决?这是一个错误吗?

最诚挚的问候,

最佳答案

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

    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) }
);
}

关于 Angular 6 : View is not updated when Subscribe method is called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50854220/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com