1. 创建公共服务
一般在公共文件内创建公共服务,命令:ng g s 路径\服务名称
如: ng g s service\storage
。得到 storage.service.ts,实现内容如下:
| import { Injectable } from '@angular/core'; |
| |
| import { BehaviorSubject } from 'rxjs'; |
| |
| @Injectable({ |
| providedIn: 'root', |
| }) |
| export class StorageService { |
| constructor() {} |
| |
| subject: BehaviorSubject<any> = new BehaviorSubject<any>(0); |
| } |
2. 在 app.module.ts 文件中引入公共 storage.service.ts 文件,并声明。
| import { NgModule } from '@angular/core'; |
| import { FormsModule } from '@angular/forms'; |
| import { BrowserModule } from '@angular/platform-browser'; |
| |
| import { AppRoutingModule } from './app-routing.module'; |
| import { AppComponent } from './app.component'; |
| import { CpmoneComponent } from './cpmone/cpmone.component'; |
| import { CpmtowComponent } from './cpmtow/cpmtow.component'; |
| |
| import { StorageService } from './service/storage.service'; |
| |
| @NgModule({ |
| declarations: [AppComponent, CpmoneComponent, CpmtowComponent], |
| imports: [BrowserModule, AppRoutingModule, FormsModule], |
| |
| providers: [StorageService], |
| bootstrap: [AppComponent], |
| }) |
| export class AppModule {} |
3. 在 A 组件
| import { Component, OnInit } from '@angular/core'; |
| |
| import { StorageService } from '../service/storage.service'; |
| import { Router } from '@angular/router'; |
| |
| @Component({ |
| selector: 'app-cpmone', |
| templateUrl: './cpmone.component.html', |
| styleUrls: ['./cpmone.component.less'], |
| }) |
| export class CpmoneComponent implements OnInit { |
| |
| constructor(public storageService: StorageService, private router: Router) {} |
| |
| ngOnInit(): void {} |
| |
| inputValue = ''; |
| |
| public send(): void { |
| this.router.navigate(['/tow']); |
| |
| this.storageService.subject.next(this.inputValue); |
| } |
| } |
4. 在 B 组件
| import { Component, OnInit } from '@angular/core'; |
| |
| import { Subscription } from 'rxjs'; |
| import { StorageService } from '../service/storage.service'; |
| |
| @Component({ |
| selector: 'app-cpmtow', |
| templateUrl: './cpmtow.component.html', |
| styleUrls: ['./cpmtow.component.less'], |
| }) |
| export class CpmtowComponent implements OnInit { |
| data: any; |
| isVisible = false; |
| |
| |
| subscription: Subscription; |
| |
| constructor(public storageService: StorageService) { |
| |
| this.subscription = this.storageService.subject.subscribe((data) => { |
| this.data = data; |
| console.log('ok'); |
| }); |
| console.log('okk'); |
| } |
| |
| showData() { |
| this.isVisible = true; |
| } |
| |
| ngOnInit(): void {} |
| |
| ngOndestry(): void { |
| |
| this.subscription.unsubscribe(); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)