【发布时间】:2018-11-15 23:13:40
【问题描述】:
所以我在 app-component 中有一个 div 集合,其中填充了我的 app-cube 组件,并且我在父组件中有一个填充有 GridProp 对象的数组,它的索引代表集合中的每个单元格,这意味着我创建了每个“单元格”的内容基于数组 [i] 的内容。
在数组 [i] 中,我有一个对象,其中包含一个 Observable 以及其他内容,例如单元格的内容。 当我更新单元格 i 中的某些内容时,我想更新单元格 [i-1] 和 [i+1] 的兄弟姐妹。
我试图通过让每个 app-cube 订阅数组中匹配对象中的 observable 来做到这一点。这样我应该能够简单地向数组中任何索引处的观察者发送一个值,并让它触发订阅的组件订阅处理程序,对吧?
数组中的对象属于这个类
export class GridProp implements OnInit {
private terrain = new Terrain();
coord: Array<number>;
cont: {};
observer: Observer<string>;
observable: Observable<string> = new Observable((observer: Observer<string>) => {
this.observer = observer;
});
}
然后在cube-component.ts中
@Component({
selector: 'app-cube',
templateUrl: './cube.component.html',
styleUrls: ['./cube.component.css']
})
export class CubeComponent implements OnInit {
@Input() point; // Represents the relevant GridProp object
ngOnInit() {
this.point.observable.subscribe(this.handleCubeUpdate);
}
handleCubeUpdate() {
console.log('handling!');
this.updateWalls();
}
updateWalls() {
// Do stuff to the "walls" values used in this cube.component.html
}
toggleWalls() {
for (const direction in this.point.cont.terrain.walls) {
if (this.getSide(direction) && this.getSide(direction).cont.terrain.isBlock) {
this.point.cont.terrain.walls[direction] = false;
this.getSide(direction).observer.next(true);
} else {
this.point.cont.terrain.walls[direction] = true;
}
}
this.updateWalls();
}
}
在父组件中,我分发了 app-cube
<div class="grid-point-z" *ngFor="let z of y">
<div
class="grid-point"
attr.data-point="{{ z.coord }}"
[ngStyle]="{
'z-index': z.coord[2]
}">
<app-cube
[point]="z"
[coord]="z"
[level]="level"
(click)="clickPoint(z)"
(change)="onCubeChange($event)">
{{z}}
</app-cube>
</div>
</div>
它因错误而崩溃
ERROR TypeError: this.updateWalls is not a function
at SafeSubscriber.push../src/app/assets/cube/cube.component.ts.CubeComponent.handleCubeUpdate [as _next] (cube.component.ts:71)
所以我猜它在 CubeComponent 的订阅中无法识别 this.handleCubeUpdate。有解决办法吗?
【问题讨论】:
-
这是一个函数
updateWalls吗?在我看来,handleCubeUpdate正在被调用,但看起来handleCubeUpdate正在调用updateWall。另外,IMO,我会在您的GridProp组件中使用Subject。 ```私人主题=新主题(); observable: Observable= subject.asObservable(); ``` -
糟糕,谢谢。我在 updateWalls 函数调用中进行了编辑。它位于 handleCubeUpdate 函数内部。我按照您的描述更改了代码,但问题是一样的。 handleCubeUpdate 能够 console.log “处理!”,但是 this.updateWalls();在崩溃日志中是“不是函数”
-
updateWalls 是在哪里声明的?正如@dK 所说,最好使用主题或行为主题。
-
并且 observable.subscribe 声明你订阅的对象 observable.subscribe(p => console.log(p); }。没有下一个,你的 observable 是没用的。
-
updateWalls 在 cube.component.ts 中声明。它处理 HTML 文件中使用的值。 .next() 稍后也会在 cube.component.ts 中调用,为了清楚起见,我会将其添加到帖子中