You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular通过服务实现组件间传参 登录后导航栏不显示用户问题求助

问题排查与修复方案

核心错误点

  • 变量名拼写错误:服务中定义的BehaviorSubject实例名为bsubject,但getMassage方法中调用的是不存在的subject变量
  • 方法名拼写不统一:
    • 服务中定义的发送消息方法是sendMassage,但app.component中调用的是不存在的send_user方法
    • 服务中定义的获取消息方法是getMassage,但main.component中调用的是不存在的getMessage方法
  • 服务未加@Injectable装饰器,没有注册到Angular依赖注入体系,会导致注入失败或者生成多个服务实例
  • 接收方订阅后只打印了消息,没有赋值给组件的massages变量,所以模板中无法显示对应内容

修复后的代码

1. db-srv-conn.service.ts 修复

import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root' // 全局单例模式,保证收发双方使用同一个服务实例
})
export class DbSrvConnService {
  private bsubject = new BehaviorSubject<any>("t");
  constructor(private http:HttpClient) { }

  sendMassage(massage: string) {
    this.bsubject.next(massage);
  }

  getMassage(): Observable<any> {
    // 修正变量名,调用实际存在的bsubject
    return this.bsubject.asObservable();
  }
}

2. app.component.ts 修复

import { DbSrvConnService } from 'src/app/sevices/db-srv-conn.service';

export class AppComponent{
  constructor(private dbSrvConnService:DbSrvConnService) { }
// ...其余原有代码
login(){
    const massage=this.formGroupLogin.value.massage;  
    if (status==1){
      // 修正调用的方法名,使用服务中实际定义的sendMassage
      this.dbSrvConnService.sendMassage(massage);
    }
}

3. main.component.ts 修复

import { DbSrvConnService } from 'src/app/sevices/db-srv-conn.service';
import { Subscription } from 'rxjs';
// ...其余原有导入

massages: any;
subscription: Subscription;

constructor(private dbSrvConnService:DbSrvConnService) { 
  // 修正调用的方法名,使用服务中实际定义的getMassage,同时将接收值赋值给组件变量
  this.subscription = this.dbSrvConnService.getMassage().subscribe(massage => {
    console.log(massage);
    this.massages = massage;
  });
}

// 组件销毁时取消订阅,避免内存泄漏
ngOnDestroy() {
  this.subscription.unsubscribe();
}

额外注意事项

不要在模块的providers数组中重复注册该服务,否则会生成多个服务实例,导致收发双方数据不通,使用providedIn: 'root'即可规避该问题。
导航栏模板中直接绑定{{massages}}或对应属性即可展示用户信息。

内容的提问来源于stack exchange,提问作者mahdi.gh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 00:48:02