Dashboard.component.ts
import { DragAndDropService } from '../api/services/drag-and-drop.service';
export class DashboardComponent {
myProperty = "hello"
constructor(private dragAndDropService: DragAndDropService) {}
ngOnInit() {
this.dragAndDropService.alterMyProperty()
}
}
DragAndDropService.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DragAndDropService {
alterMyProperty() {
this.myProperty = "New String we are trying to alter";
}
}
因此,由于范围的原因,这当然是行不通的。该服务将在它自己的类中查找“this.myProperty”。但是有没有办法让它默认到实例化的范围(在这种情况下,Dashboard.component 的构造函数)?
这个例子非常简单,为了简洁我省略了代码。我的实际代码比这复杂得多。
最佳答案
我不确定您为什么不想使用 Rxjs。但这会让您的生活变得轻松。
您可以从服务本身设置组件的属性。
试试这个:
Dashboard.component.ts
import { DragAndDropService } from '../api/services/drag-and-drop.service';
export class DashboardComponent {
myProperty = "hello"
constructor(private dragAndDropService: DragAndDropService) {}
ngOnInit() {
this.dragAndDropService.alteredProperty$
.subscribe(alertedProperty => this.myProperty = alertedProperty);
}
}
DragAndDropService.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DragAndDropService {
private alteredProperty: BehaviorSubject<string> = new BehaviorSubject<string>(null);
alteredProperty$: Observable<string> = this.alteredProperty.asObservable();
alterMyProperty(alteredProperty) {
this.alteredProperty.next(alteredProperty);
}
}
您现在可以在任何地方注入(inject) DragAndDropService
以调用它的 alterMyProperty
方法并将 alteredProperty
的值传递给它。一旦调用此方法,它就会通知 DashboardComponent,因为它正在订阅
alteredProperty$
Observable。
关于javascript - Angular 服务是否可以直接更改注入(inject)它的组件的属性(没有商店/RxJs)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53177788/