简体   繁体   English

如何从登录组件到angular中的另一个组件获取sessionStorage的值

[英]How to get value of sessionStorage from login component to another component in angular

I want to store user id in sessionStorage and get in blogcomponent how to get please help me.. 我想将用户ID存储在sessionStorage中,并在blogcomponent中获取如何获取,请帮助我。

loginComponente.ts loginComponente.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NgFlashMessageService } from 'ng-flash-messages';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AuthenticationServiceService } from '../_services';
import { AlertService } from '../_services';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  msg: string = null;
  loading = false;
  submitted = false;
  returnUrl: string;
  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    public router: Router,
    public flashMessageService: FlashMessagesService,
    private authenticationService: AuthenticationServiceService,
    private alertService: AlertService) { }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      email: ['', Validators.required],
      password: ['', Validators.required],
    });

    if (!this.authenticationService.setLoginStatus) {
      this.router.navigate(['login']);
    }


    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['/'] || '/';
  }
  get f() { return this.loginForm.controls; }

  onSubmit() {
    // if form valid then call authentication API 
    if (this.loginForm.valid) {
      this.submitted = true;
      // this.loading = true;
      this.authenticationService.login(this.f.email.value,
        this.f.password.value)
        .pipe(first())
        .subscribe(
          data => {
            if (data.status === false) {
              alert("Please enter valid Email Or Password");
              this.router.navigate(['login']);

              this.authenticationService.setLoginStatus(0);

            }
            else {

              this.flashMessageService.show('You have successfully logged in',
                { cssClass: 'alert-success', timeout: 3000 });
              this.router.navigate(['blog-list']);
              sessionStorage.setItem('currentUser',data.id);
              var users = sessionStorage.getItem('currentUser');
              // console.log("You have successfully logged in");
              console.log(users);
            }
          },
          error => {
            this.alertService.error(error);
            this.loading = false;
          });
    }
  }

}

I want to get login user id in blog-list componenet in ngoninit function is getUserBlogById() but its gives error how to get id in getUserBlogid() please help me. 我想在ngoninit函数中的博客列表componenet中获取登录用户ID是getUserBlogById(),但它给出了如何在getUserBlogid()中获取ID的错误,请帮助我。

blog-list.component.ts 博客,list.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { UserService } from '../_services';
import { User } from '../_models'
import { FlashMessagesService } from 'angular2-flash-messages';
import { AuthenticationServiceService } from '../_services';
@Component({
  selector: 'app-blog-list',
  templateUrl: './blog-list.component.html',
  styleUrls: ['./blog-list.component.css']
})
export class BlogListComponent implements OnInit, OnDestroy {
  currentUser: User;
  msg: string = null;
  id: number;
  currentUserSubscription: Subscription;
  users: User[] = [];

  constructor(

    public router: Router,
    public flashMessageService: FlashMessagesService,
    private authenticationService: AuthenticationServiceService,
    private userService: UserService
  ) {
    this.currentUserSubscription = this.authenticationService.currentUser.subscribe(user => {
      this.currentUser = user;


    });
  }

  ngOnInit() {

    this.getUserBlogById(1);
  }
  ngOnDestroy() {

    // unsubscribe to ensure no memory leaks
    this.currentUserSubscription.unsubscribe();

  }

  deleteUser(id: number) {
    this.userService.delete(id).pipe(first()).subscribe(() => {
      //this.getUserBlogById(this.id);
      this.flashMessageService.show('Blog deleted successfully.',
      { cssClass: 'alert alert-danger alert-dismissible fade in', timeout: 3000 });
    });
}

  private getUserBlogById(id:number) {

    this.userService.getAll(id).pipe(first()).subscribe(users => {
      this.users = users;
    });
  }


}

how to use sessionStorage value in blog-list.component , i want to show blog of user logged in please help me how to resolve this type of problem . 如何在blog-list.component中使用sessionStorage值,我想显示已登录用户的博客,请帮助我如何解决此类问题。 Thank you in advance... 先感谢您...

You can access the session storage item in ngOnInit() lifecycle hook that was set in loginComponente.ts 您可以访问在loginComponente.ts设置ngOnInit()生命周期挂钩会话存储项目

blog-list.component.ts 博客,list.component.ts

ngOnInit() {
  //here you can access your sessionstorage item like
   let currentUserId= sessionStorage.getItem('currentUser');
    this.getUserBlogById(currentUserId);
  }

The first thing is in your Login Component You need to add item in session storage before you Redirect Further ; 第一件事是在登录组件中,您需要在会话存储中添加项目,然后再进行进一步重定向

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NgFlashMessageService } from 'ng-flash-messages';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AuthenticationServiceService } from '../_services';
import { AlertService } from '../_services';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  msg: string = null;
  loading = false;
  submitted = false;
  returnUrl: string;
  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    public router: Router,
    public flashMessageService: FlashMessagesService,
    private authenticationService: AuthenticationServiceService,
    private alertService: AlertService) { }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      email: ['', Validators.required],
      password: ['', Validators.required],
    });

    if (!this.authenticationService.setLoginStatus) {
      this.router.navigate(['login']);
    }


    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['/'] || '/';
  }
  get f() { return this.loginForm.controls; }

  onSubmit() {
    // if form valid then call authentication API 
    if (this.loginForm.valid) {
      this.submitted = true;
      // this.loading = true;
      this.authenticationService.login(this.f.email.value,
        this.f.password.value)
        .pipe(first())
        .subscribe(
          data => {
            if (data.status === false) {
              alert("Please enter valid Email Or Password");
              this.router.navigate(['login']);

              this.authenticationService.setLoginStatus(0);

            }
            else {

              this.flashMessageService.show('You have successfully logged in',
                { cssClass: 'alert-success', timeout: 3000 });
               sessionStorage.setItem('currentUser',data.id);
               var users = sessionStorage.getItem('currentUser');
               // console.log("You have successfully logged in");
               console.log(users);
              this.router.navigate(['blog-list']);
            }
          },
          error => {
            this.alertService.error(error);
            this.loading = false;
          });
    }
  }

}

On you Other component's Onint life cycle hook as: 在您身上,其他组件的Onint生命周期挂钩如下:

ngOnInit() {
//'+' operator will convert string into number
    var userId = +sessionStorage.getItem('currentUser');
    this.getUserBlogById(userId);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM