Angular 如何在所有页面或组件中成功登录后获取用户详细信息(emailid)

Angular 如何在所有页面或组件中成功登录后获取用户详细信息(emailid),angular,typescript,Angular,Typescript,我不熟悉棱角和打字。我有8页,包括登录和注册页面在我的角度项目。我需要用户配置文件数据,例如每个页面中的电子邮件id。我尝试通过emit函数向每个组件发送电子邮件,但这并不可靠,因为每当我们刷新页面时,数据都会丢失。有人能给我推荐一个简单有效的方法来获取我项目中每个页面/组件的电子邮件id吗 下面是我的login.ts文件 import { Component, OnInit } from '@angular/core'; import { Router, Act

我不熟悉棱角和打字。我有8页,包括登录和注册页面在我的角度项目。我需要用户配置文件数据,例如每个页面中的电子邮件id。我尝试通过emit函数向每个组件发送电子邮件,但这并不可靠,因为每当我们刷新页面时,数据都会丢失。有人能给我推荐一个简单有效的方法来获取我项目中每个页面/组件的电子邮件id吗

下面是我的login.ts文件

        import { Component, OnInit } from '@angular/core';
        import { Router, ActivatedRoute } from '@angular/router'; 
        import { Input, Output, EventEmitter } from '@angular/core';
        import { FormGroup, FormControl } from '@angular/forms';
        import { DataService } from '../services/data.service'
        import {EventtosymptomsService } from '../services/eventtosymptoms.service';
        interface loginInfo
        {
          email: string;
          password: string;
        }
        interface Response{
          result: boolean;
        
        }
        @Component({
          selector: 'app-login',
          templateUrl: './login.component.html',
          styleUrls: ['./login.component.css']
        })
        export class LoginComponent implements OnInit {
          constructor(private router: Router, private route: ActivatedRoute, private dataService: DataService, private eventService: EventtosymptomsService ) { }
          isShown: boolean = true ; // default will be Patient Login
          
          PemailId:string = "";
          Ppassword:string = "";
          logininfo ={} as loginInfo;
          response = {} as Response;
          error_message:boolean = false;
          sendData:string;
          toggleShow() {
          console.log("In toggle show")
          this.isShown = ! this.isShown;
          this.error_message = false;
          }
         
      patientLogin(patient_emailid: string, patient_password: string)
      {
    
        this.logininfo.email = patient_emailid;
        this.logininfo.password = patient_password;
        console.log(this.logininfo)
        this.sendData = patient_emailid;
        this.loginCheckPatient()
        
      }
    
      Register()
      {
        console.log("hello")
        this.router.navigate(['register']);
    
      }
            loginCheckPatient() {
                this.dataService.loginCheck(this.logininfo)
                  .subscribe(data => {
                    console.log(data)
                    this.response = data;
                    if(this.response.result)
                  {
                    console.log("In response check", this.response["result"])
                    this.error_message = false
                    this.eventService.emit<{}>(this.sendData);
                    this.router.navigate(['analyseSymptoms']);
                  }
                  else{
                        console.log("In else")
                          this.error_message = true;
                  }
                  }
                  )
                  
              }
}
    

    
从'@angular/core'导入{Component,OnInit};
从'@angular/Router'导入{Router,ActivatedRoute};
从“@angular/core”导入{Input,Output,EventEmitter};
从'@angular/forms'导入{FormGroup,FormControl};
从“../services/data.service”导入{DataService}
从“../services/eventtosymmptoms.service”导入{eventtosymmptomservice};
接口登录信息
{
电子邮件:字符串;
密码:字符串;
}
界面响应{
结果:布尔型;
}
@组成部分({
选择器:“应用程序登录”,
templateUrl:'./login.component.html',
样式URL:['./login.component.css']
})
导出类LoginComponent实现OnInit{
构造函数(专用路由器:路由器,专用路由:ActivatedRoute,专用数据服务:数据服务,专用事件服务:EventToSymmptomService){}
isShown:boolean=true;//默认值为患者登录
PemailId:string=“”;
Ppassword:string=“”;
logininfo={}作为logininfo;
response={}作为响应;
错误消息:布尔值=false;
sendData:字符串;
切换显示(){
console.log(“在切换显示中”)
this.isShown=!this.isShown;
this.error_message=false;
}
patientLogin(患者\电子邮件ID:string,患者\密码:string)
{
this.logininfo.email=patient\u emailid;
this.logininfo.password=患者密码;
console.log(this.logininfo)
this.sendData=患者\电子邮件ID;
this.loginCheckPatient()
}
寄存器()
{
log(“你好”)
这个.router.navigate(['register']);
}
登录检查患者(){
this.dataService.loginCheck(this.logininfo)
.订阅(数据=>{
console.log(数据)
这个响应=数据;
if(this.response.result)
{
console.log(“响应检查”,this.response[“result”])
this.error\u message=false
this.eventService.emit(this.sendData);
this.router.navigate(['analyseSymptoms']);
}
否则{
console.log(“在其他地方”)
this.error_message=true;
}
}
)
}
}
下面是我的服务代码文件(dataservice.ts)

从'@angular/core'导入{Injectable};
从“@angular/common/http”导入{HttpClient,HttpErrorResponse};
从“rxjs”导入{Observable};
从“rxjs”导入{throwError};
从“rxjs/operators”导入{catchError};
从'rxjs/ajax'导入{ajax};
@注射的({
providedIn:'根'
})
导出类数据服务{
LoginPartient_url=”http://127.0.0.1:5000/api/loginPatient"
构造函数(私有httpClient:httpClient){}
登录检查(个人):可观察{
const headers={'content type':'application/json'}
const body=JSON.stringify(person);
控制台日志(正文)
返回this.httpClient.post(this.loginpartient_url,body,{'headers':headers})
}
}

您可以使用行为主题 BehaviorSubject保存需要与其他组件共享的值。 这些组件订阅的数据只返回BehaviorSubject值,而不具有更改值的功能。 下面是一个更详细的asObservable细分。在updateDataSelection中,我们调用next并将新值传递给BehaviorSubject。 首先创建一个服务,如下所示

`import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { loginInfo } from '../entities/data';

@Injectable()
export class DataService {

  private dataSource = new BehaviorSubject<loginInfo>(new loginInfo());
  data = this.dataSource.asObservable();

  constructor() { }

  updatedDataSelection(data: loginInfo){
    this.dataSource.next(data);
  }
  
}`

Use above service in all the components where you want user details

`//inject service into component

dataService.data.subscribe(data => {
  //do what ever needs doing when data changes
})

//update the value of data in the service
dataService.updateData(newData);
从'@angular/core'导入{Injectable};
从'rxjs/BehaviorSubject'导入{BehaviorSubject};
从“../entities/data”导入{loginInfo};
@可注射()
导出类数据服务{
私有数据源=新行为主体(新登录信息());
data=this.dataSource.asObservable();
构造函数(){}
updatedDataSelection(数据:loginInfo){
this.dataSource.next(数据);
}
}`
在需要用户详细信息的所有组件中使用上述服务
`//将服务注入组件
dataService.data.subscribe(数据=>{
//当数据发生变化时,做任何需要做的事情
})
//更新服务中数据的值
dataService.updateData(newData);

您可以将其存储在localstorage或cookie中,并使用服务访问它
`import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { loginInfo } from '../entities/data';

@Injectable()
export class DataService {

  private dataSource = new BehaviorSubject<loginInfo>(new loginInfo());
  data = this.dataSource.asObservable();

  constructor() { }

  updatedDataSelection(data: loginInfo){
    this.dataSource.next(data);
  }
  
}`

Use above service in all the components where you want user details

`//inject service into component

dataService.data.subscribe(data => {
  //do what ever needs doing when data changes
})

//update the value of data in the service
dataService.updateData(newData);