我想将值从一项服务传递给另一项服务。
我将FirstService中的值设置为可观察到,然后SecondService订阅该值。更改值后,服务将做出反应。
“ first.service.ts”
export class FirstService extends Service {
private readonly firstValue =
new BehaviorSubject<string>('');
getFirstValue(): Observable<string> {
return this.firstValue;
}
setFirstValue(value: string) {
this.firstValue.next(value);
}
}
“ second.service.ts”
export class SecondService extends Service {
private secondValue: string;
constructor(http: HttpClient, private firstService: FirstService ) {
super(http);
firstService.getFirstValue().subscribe(
(val) => {
this.secondValue = val;
}
);
}
}
但是,每当我输入SecondService组件的url时,都会重新构造Service(SecondService),并且它所订阅的Service(FirstService)也将初始化。因此我丢失了之前设置的值。
我应该怎么做才能将该值传递给服务。非常感谢!
答案 0 :(得分:0)
@Injectable({
providedIn: 'root',
})
export class FirstService extends Service {
firstValue = new BehaviorSubject<string>('');
$firstValue = this.firstValue.asObservable();
setFirstValue(value: string) {
this.firstValue.next(value);
}
}
并删除模块和组件中对第一服务的任何引用。 在第二项服务中:
firstService.firstValue$.subscribe(val => this.secondValue = val);
如果您不想每次都不初始化第一服务,则应将root
参数放入注入器。
从'@ angular / core'导入{可注射};
@Injectable({
providedIn: 'root',
})
export class UserService {
}
有关更多信息:https://angular.io/guide/singleton-services
有关更多信息:https://indepth.dev/angulars-root-and-any-provider-scopes/