首页 > 解决方案 > 无法以角度将值传递给组件

问题描述

我想将一个服务的值传递给另一个服务。

我将 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);
    }
}

“第二个.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的Component的url,Service(SecondService)都会被重构,它订阅的Service(FirstService)也会被初始化。所以我失去了我之前设定的价值。

我应该怎么做才能将值传递给服务。非常感谢!

标签: angular

解决方案


@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/


推荐阅读