在不相关的组件之间共享数据

时间:2018-07-10 09:48:06

标签: angular

第一个加载页面是登录名,它重定向到菜单/事务组件。

我必须将登录响应的数据传递给我的交易组件。我不想使用会话存储。

我尝试了其他方法,但是没有用。

您可能会看到我也尝试过BehaviorSubject,但没有成功

// Loginservice.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { BehaviorSubject } from 'rxjs';
//import 'rxjs/add/operator/map';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

    constructor(private http: HttpClient) { }   

    configUrl = environment.authenticateURL;
    private loginResponse = new BehaviorSubject('default');
    currentResponse = this.loginResponse.asObservable();

    getAuthentication = function (sysId, user, pwd) {
        const loginHeaders = new HttpHeaders();
        const body = {
            "username": user,
            "password": pwd,
            "systemId": sysId 
        }; 
        sessionStorage.setItem("sysID", sysId);
        loginHeaders.append("Access-Control-Allow-Origin", "true");
        loginHeaders.append("Content-Type", "application/json");
        return this.http.post(this.configUrl, body, loginHeaders);
    }
}

// Logincomponent.ts

import { Component, OnInit } from '@angular/core';
import { RouterModule, Routes, Router } from '@angular/router';
import { LoginService } from '../../service/login/login.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SpinnerComponent } from '../../Template/Spinner';
import { environment } from '../../../environments/environment';
//import { Observable } from 'rxjs';
//import 'rxjs/add/observable/of';
//import 'rxjs/add/operator/map';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [LoginService]
})
export class LoginComponent implements OnInit {

    baseHref: string = environment.baseHref;

    form: FormGroup;

    constructor(private router: Router, private _data: LoginService, private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.form = this.formBuilder.group({
            systemId: ['', Validators.required],
            user: ['', Validators.required],
            pwd: ['', Validators.required]  
        });
       // this.form.valueChanges.subscribe(data => console.log(JSON.stringify(data)));
    }

    get f() {
        return this.form.controls;
    }
    public spinner;
    public loginPermissions;
    loginReDirect = function () {
        let sysId = this.form.controls.systemId.value;
        let user = this.form.controls.user.value;
        let pwd = this.form.controls.pwd.value;
       // this.router.navigateByUrl('menu');
        this.spinner = true;
        // let authentication = this._data.getAuthentication(sysId, user, pwd);
        let authentication = this._data.getAuthentication..subscribe(
            success => {
                if (success.status == "1") {
                    this.currentResponse.next(success);
                    sessionStorage.setItem("permissions", JSON.stringify(success.permissions));
                    sessionStorage.setItem("token", success.token);

                    let loginPermission = success.permissions;
                    let systemId = success.token;

                    //Transaction Module
                    if (loginPermission["TRANSACTIONS"]) {
                        this.loginPermissions = JSON.stringify(loginPermission["TRANSACTIONS"]);
                    }

                    console.log(success);
                } else {

                }
            }, error => {
                console.log(error);
                this.spinner = false;
            }
        );   
    }

}

//路由配置

const appRoutes: Routes = [
    { path: '', component: LoginComponent },
    //{ path: 'menu', loadChildren: './modules/menu/Menu.module#MenuModule' }
    {
        path: 'menu',
        component: MenuComponent,
        children: [{
            path: 'transactions', component: TransactionsComponent
        }]

    },

1 个答案:

答案 0 :(得分:0)

*您可以使用:

传递参数
this.router.navigate([redirectUrl, data]);

并按以下方式获取另一个组件中的数据:

constructor(
        private router: Router,
        private route: ActivatedRoute,
    ) 

this.route.paramMap.subscribe(param => {
            this.data = Number(param.get('data'));
        });

*您还可以使用@Input装饰器

传递参数
<child-component [data]="data"></child-component>

在子组件中使用@Input接收数据:

@Input() data: any;

ngOnInit(){

console.log(this.data)

}