要解决Angular + ngfire 2中构造函数中声明的变量未被正确分配的问题,可以按照以下步骤进行:
import { Component } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
myVariable: string = '';
constructor(private afDb: AngularFireDatabase) {}
ngOnInit() {
// 在这里可以使用myVariable变量
this.myVariable = 'Hello World!';
}
}
{{ myVariable }}
import { Component } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
myVariable: string = '';
constructor(private afDb: AngularFireDatabase) {}
ngOnInit() {
// 异步获取数据
this.afDb.object('path/to/data').valueChanges().subscribe((data: string) => {
// 在数据获取成功后分配变量
this.myVariable = data;
});
}
}
通过按照以上步骤检查和调整代码,你应该能够解决Angular + ngfire 2中构造函数中声明的变量未被正确分配的问题。