- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题是基于这个问题的(提供的解决方案不起作用): 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/
我正在使用 Swift Joint,但不明白两者之间的区别 func subscribe(_ subscriber: S) where S : Subscriber, Self.Failure ==
大多数 Flowable.subscribe() 重载返回一个 Disposable ,它可以清理流。我习惯于这样做: Disposable d = Flowable.just() .map(
我正在尝试测试主题 symbol$ 的输出存在于我的组件上。 具体来说,当组件属性 symbol 时,主题符号 $ 应该发出(这是正确的词吗?)已经改变。 但是,我找不到测试输出到 symbol$ 的
Observable.just(10,20,30,40,50) .subscribe { Consumer{ Log.d(TAG, "Where
我在 subscribe 中有带有 subscribe 的代码: this.http.post('/update1', newData).subscribe( (response) => {
我有两个页面/模板, 仪表板(还包含一些用户特定数据)。 用户。 我正在使用带有 Blaze 模板的 Meteor 1.5。登陆页面是仪表板。我在两个模板中都使用集合 Users 的通用订阅。 场景
我刚接触 Angular2 一周! 基本上有 2 个 API 调用。 第一个 API 调用为我提供了一个 json 对象数组 (queryResults)。 (第一次订阅) 在 View 中显示该数组
我已经在 stackoverflow 上尝试了很多关于修复此错误的提议,但现在我只需要问一下,因为我已经花了很多时间,现在一无所获。 我有这个简单的服务: constructor(private ht
给定一个配置有任务执行器的发布-订阅 channel ,如果抛出异常,是否可以中断其有序订阅者的调用? 例如,在此示例中,“已工作”消息仍然由序列中的第二个服务激活器发送。我希望这种事不要发生。
我正在尝试使用 Intent to PDF 应用程序下载和发送 pdf 以显示此处显示的文件 answer of JDenais这是下载 pdf 并通过 Intent 传递它的代码。 public c
我目前正在调查 RxJS's .merge但是我也会在这里问这个问题,因为我发现这里的解释有时非常精彩。 好的,我有一个根据用户输入打开模态窗口的表单,我订阅模态关闭事件并传回一些我将在调用/订阅服务
我刚刚对我的 Angular 6 应用程序进行了 ng 升级,现在我得到: ERROR in node_modules/@angular/flex-layout/core/typings/observ
如果您有一个事件驱动的架构并且订阅事件的服务在继续创建链中的下一个事件之前必须等待多个事件(相同类型),那么最佳实践是什么? 一个例子是图书订单处理服务,它必须等待订单中的每一本书都被仓库处理,然后再
我使用下面的代码进行异步调用,我想知道在 getData() 函数中生成的 data 的值,但是,我得到 undefined 因为调用还没有解决。有什么办法可以解决吗? getData(address
我在订阅我的 HTML 页面中的下拉值更改时遇到实现 knockout Js 的问题。这是我的 HTML Request Types :
函数定义 resetComponent(){ console.log("1st"); ... this.background = { }; this.uploadMode = fals
在我的代码中,我正在使用 @Subscribe 注释来监听事件: @Subscribe public void orderUpdate(OrderUpdateEvent event) 我的问题是,对于
我正在使用 Angular2 和 NodeJS 编写 API,我正在为我的 ِAPI 实现服务,该 API 应该获取任务列表并显示它。这是任务服务: import {Injectable} from
我正在尝试使用来自服务器的 json 响应创建动态菜单,但出现此错误: MenuComponent.html:4 ERROR TypeError: Cannot read property 'subs
我查看了许多资源,包括 this , this和 this ,但我一直无法达到预期的效果。 我要做的就是验证用户(使用 firebase),然后在验证后加载他们的配置文件并将其存储在变量 userPr
我是一名优秀的程序员,十分优秀!