【发布时间】:2020-07-23 22:45:00
【问题描述】:
我完全绝望地来找你......从 1 天开始,我尝试使用服务在我的两个组件之间传递数据。
我已经在另一个应用程序中使用了此服务,并且我知道它可以正常工作。
但是我已经尝试了使用谷歌搜索找到的所有东西:BehaviorSubject、Subject ... 但在我的情况下没有任何效果:由于第一个组件,服务中的值发生了变化,但在第二个组件,即使我订阅了服务中的价值。
第二个组件在初始化时获得值,但在...之后什么都没有
提示:第二个组件是第一个组件的父组件。
这是我的代码(实际上):
GlobalFn.Service :
import { Injectable } from '@angular/core'
import { Observable, Subject, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class globalFnService{
id:any;
activeDeepView = new Subject<boolean>();
constructor() {
this.activeDeepView.next(false);
}
deepView(){
this.activeDeepView.next(!this.activeDeepView);
}
getValue(): Observable<any> {
return this.activeDeepView.asObservable();
}
}
第一个组件(子):
import { Component, OnInit } from '@angular/core';
import { globalFnService } from '../services/globalFn.service';
@Component({
selector: 'app-profil',
templateUrl: './profil.component.html',
styleUrls: ['./profil.component.scss'],
providers: [globalFnService]
})
export class ProfilComponent implements OnInit {
constructor(
private globalFn:globalFnService
) {
}
deepView(){
this.globalFn.deepView();
console.log("clicked !");
}
ngOnInit() {
this.globalFn.getValue().subscribe(value => {
if(value == true){
console.log("status",value);
} else {
console.log("status",value);
}
})
}
}
第二个组件(父组件):
import { Component, OnInit } from '@angular/core';
import { globalFnService } from '../services/globalFn.service';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss']
})
export class HomeComponent implements OnInit {
constructor(
private globalFn:globalFnService
) {
this.subscription = this.globalFn.getValue().subscribe(value => {
if(value == true){
console.log("status",value);
} else {
console.log("status",value);
}
})
}
}
如果你能找到我做错的地方,你就有能力拯救我的一天......
谢谢!
【问题讨论】:
-
您到底希望发生什么?
-
必须在模块
providers: [globalFnService]提供服务 -
显示 app.module.ts
-
我忘记在我的 app.module.ts 中添加它...我会尝试添加它,我来找你!
-
@PositivProd 不要将其添加到您的应用模块中。