代码之家  ›  专栏  ›  技术社区  ›  Krishna Chaitanya

在角度组件之间共享数据

  •  0
  • Krishna Chaitanya  · 技术社区  · 6 年前

    我想在两个组件之间共享角度数据。我照解释的做了 here here

    登录.component.ts

    import { Component, OnInit } from '@angular/core';
    import { User } from '../domain/User';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { LoginResponse } from '../domain/LoginResponse'
    import { DataSharingService } from '../service/DataSharingService';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css'],
      providers: [DataSharingService]
    })
    export class LoginComponent implements OnInit {
    
      private user:User = new User();
    
      private xSSOFamilyId:string = 'BOMO';
    
      constructor(private httpClient: HttpClient, private dataSharingService: DataSharingService, private router: Router) { }
    
      ngOnInit() {
      }
    
      login(): void {
    
        var authorization:string = 'Basic ' + btoa(this.user.cwopa + ":" + this.user.password);
        var httpHeaders = new HttpHeaders({
          'Authorization': authorization,
          'userId': this.user.cwopa,
          'X-SSO-Family-Id': this.xSSOFamilyId
        });
        this.httpClient.post<LoginResponse>('http://localhost:8081/web-beginner/authenticate', undefined, {headers: httpHeaders}).subscribe(response => {
          this.router.navigate(['dashboard'])
        }, error => {
          console.log("error occured");
        });
      }
    
      public getApiKey() {
        this.dataSharingService.setData({apikey: '1234'});
      }
    
    }
    

    仪表板.component.ts

    import { Component, OnInit } from '@angular/core';
    import { DataSharingService } from '../service/DataSharingService';
    import { LoginComponent } from '../login/login.component';
    
    @Component({
      selector: 'app-dashboard',
      templateUrl: './dashboard.component.html',
      styleUrls: ['./dashboard.component.css'],
      providers: [DataSharingService, LoginComponent]
    })
    export class DashboardComponent implements OnInit {
    
      constructor(private dataSharingService: DataSharingService, private loginComponent: LoginComponent) { }
    
      ngOnInit() {
        this.dataSharingService.currentData.subscribe(data => {
          console.log(data)
        });
      }
    
      authorize(appName:string): void {
        console.log(this.loginComponent.getApiKey())
      }
    }
    

    我在dashboard.component.html中有一个链接。每次单击它,都会调用onNgInit和authorize函数。

    此外,dashboard.component.ts的authorize函数中要接收的数据是print undefined,onNgInit正在打印期望值。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Asanka    6 年前

    从登录组件中删除提供程序:[DataSharingService]将DataSharingService添加到app.module.ts提供程序中,使其成为singleton。

    不要像这样通过构造函数注入组件。

    private loginComponent: LoginComponent
    

    只需使用服务共享数据,或者如果DashboardComponent.html包含LoginComponent作为组件,则可以使用@ViewChild作为Sujay的答案。

        2
  •  0
  •   Sujay    6 年前

    你需要得到 LoginComponent 使用 @ViewChild 关键字

        import { Component, OnInit } from '@angular/core';
        import { DataSharingService } from '../service/DataSharingService';
        import { LoginComponent } from '../login/login.component';
    
        @Component({
          selector: 'app-dashboard',
          templateUrl: './dashboard.component.html',
          styleUrls: ['./dashboard.component.css'],
          providers: [DataSharingService, LoginComponent]
        })
        export class DashboardComponent implements OnInit {
        @ViewChild(LoginComponent) loginComponent: LoginComponent
          constructor(private dataSharingService: DataSharingService) { }
    
          ngOnInit() {
            this.dataSharingService.currentData.subscribe(data => {
              console.log(data)
            });
          }
    
          authorize(appName:string): void {
            console.log(this.loginComponent.getApiKey())
          }
        }