我们如何在两个组件之间共享数据 - 两者都是完全独立的组件.(不在子父关系中)



我们如何在两个组件之间共享数据 - 两者都是完全独立的组件?(不属于子父母关系(

我想在我的标头组件中显示注册组件的变量"totalReg"值。两个文件都在下面。

这是我的注册表组件

import { Component, Output } from '@angular/core';
import { UserService } from '../services/reg.service';
import { VERSION } from '@angular/core';
@Component({
templateUrl: 'reg.component.html'
})
export class RegComponent {

    constructor(
    private userService: UserService,
    ) { }
@Output() totalReg: any;
register(event: any) {
    this.userService.create(event.target.username.value)
        .subscribe(
            data => {
                this.totalReg = data['data'].userId;
                console.log(this.totalReg); // Navigate to the 
listing aftr registration done successfully
            },
            error => {
                console.log(error);
            });
    }
}

这是我的标头.component.ts 从"@angular/核心"导入 { 组件, OnInit };

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

这是我的标头组件 header.component 的 html.html

<div class="container">
<mat-toolbar>  
                <ul class="nav navbar-nav">
                    <li><a [routerLink]="['/login']">Login</a></li>
                    <li><a [routerLink]="['/reg']">Registration</a> 
   </li>
                    <li><a [routerLink]="['/users']">All Users</a> 
   </li>
                </ul>
    </mat-toolbar>
    <span>{{totalReg}}</span>
    </div>

标头组件应显示 totalReg 的值。

您可以在服务类的帮助下执行此操作。

您已经在RegComponent 中使用用户服务,因此请在HeaderComponent中使用相同的服务来获取数据。

HeaderComponent.ts

export class HeaderComponent implements OnInit {
  totalReg: any;
  constructor(private service : UserService) { }
  ngOnInit() {
    this.totalReg = this.service.totalRg;
  }
}

RegComponent.ts

export class RegComponent {
@Output() totalReg: any;
constructor(private userService: UserService) { }
register(event: any) {
   this.userService.create(event.target.username.value)
        .subscribe(data => {
               this.totalReg = data['data'].userId;
               console.log(this.totalReg); // Navigate to the listing aftr registration done successfully
               this.service.totalRg = this.totalReg;
            },
            error => {
                console.log(error);
        });
    }
}

您已经在服务类中使用了一个类,您需要将变量添加为 totalRg

UserService.ts

export class UserService {
  totalRg:any;
  constructor() { }
  create(name: any) {
    return ....//
  }
}

最新更新