我在Angular 7上遇到了一个非常奇怪的情况。我在ngOnInit中使用异步调用填充了一个数组,尽管我确认该调用之后已填充了该数组,但是当我稍后尝试使用它时,它为空。
ngOnInit的生命周期中是否存在某些东西会导致阵列被擦除?
我的配置是:
Angular CLI: 7.1.4
Node: 11.3.0
OS: darwin x64
Angular: 7.1.4
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.11.4
@angular-devkit/build-angular 0.11.4
@angular-devkit/build-optimizer 0.11.4
@angular-devkit/build-webpack 0.11.4
@angular-devkit/core 7.1.4
@angular-devkit/schematics 7.1.4
@angular/cdk 7.2.0
@angular/material 7.2.0
@ngtools/webpack 7.1.4
@schematics/angular 7.1.4
@schematics/update 0.11.4
rxjs 6.3.3
typescript 3.1.6
webpack 4.23.1
代码如下(为了简化代码,我删除了所有错误处理调用,并可以确认未引发任何错误):
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { CurrencyWindow } from './currency-transaction-window';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
baseURL = 'http://localhost/api/';
currencyTransactionWindows: CurrencyWindow[];
constructor( private http: HttpClient ) { }
setRootCurrency( ) : void {
if ( !!this.currencyTransactionWindows ) {
// do something
} else {
console.log("Something wrong - we lost our transaction windows!");
}
}
determineAvailableCurrencies( transactionWindows: CurrencyWindow[]) {
this.currencyTransactionWindows = transactionWindows;
if (!this.currencyTransactionWindows ) {
console.log("Failed to get currency transactions");
} else {
console.log( this.currencyTransactionWindows.length + " currency transaction windows found ");
}
}
getCurrencyTransactionWindows( ): Observable<CurrencyWindow[]> {
return this.http.get(`${this.baseURL}/select.php`).pipe(
map((res) => { return res['data']; }) );
}
ngOnInit() {
this.getCurrencyTransactionWindows( )
.subscribe( this.determineAvailableCurrencies );
}
}
导入数据的类为:
export class CurrencyWindow {
constructor(
public currencySource: string,
public currencyTarget: string,
public firstDate: Date,
public lastDate: Date
) {}
}
用于应用程序根目录的HTML是:
<button (click)="setRootCurrency()">Click me!</button>
控制台输出为:
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
app.component.ts:43 15 currency transaction windows found
app.component.ts:30 Something wrong - we lost our transaction windows!
有人可以帮助我了解我在做什么错吗?
答案 0 :(得分:0)
尝试一下
width:100;
或此
this.getCurrencyTransactionWindows( )
.subscribe( this.determineAvailableCurrencies.bind(this) );
恕我直言,数据永远不会绑定到组件字段。
答案 1 :(得分:0)
我曾经有过类似的奇怪行为,结果是我单击按钮后Chrome正在提交表单。
在这种情况下,解决方法是在html中添加type =“ button”,所以在您的情况下:
<button type="button" (click)="setRootCurrency()">Click me!</button>