Angular2:将值从一个组件传递到另一个组件

时间:2017-01-03 19:02:25

标签: javascript angular typescript

我已成功为我的Angular 2应用程序实现了登录服务。我现在要做的是将登录用户的用户名从该组件提供给一个单独的组件 - 特别是聊天组件。这样我可以在与其他用户聊天时显示用户的姓名。我对如何在Angular 2中将这样的值从一个组件传递到另一个组件仍然有点朦胧。以下是我的登录组件中的代码:

import { AuthenticationService } from './../../data/authentication.service';
import { AlertService } from './../../data/alert.service';
import { Component, OnInit, Output } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    selector: 'app-login',
    templateUrl: 'app/views/login/login.component.html',
    styleUrls: ['app/views/login/login.component.css']
})

export class LoginComponent implements OnInit {
    //@Output() username;
    model: any = {};
    loading = false;

    constructor(
        private router: Router,
        private authenticationService: AuthenticationService,
        private alertService: AlertService) { }

    ngOnInit() {
        // reset login status
        this.authenticationService.logout();
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
                data => {
                    this.router.navigate(['/']);
                    console.log('User logged in as: ' + this.model.username);
                },
                error => {
                    this.alertService.error(error);
                    this.loading = false;
                });
    }

    reqPasswordReset() {
        let popup = document.getElementById('myPopup');
        popup.classList.toggle('show');
    }
}

此组件使用身份验证服务,如下所示:

import { LoginComponent } from './../views/login/login.component';
import { ContextMenu } from './../ui/context-menu.component';
import { Router, RouterLinkActive } from '@angular/router';
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthenticationService {

    constructor(private http: Http) {}

    login(username: string, password: string) {
        return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let user = response.json();
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }
            });
    }

    isAuthenticated() {
        if (localStorage.getItem('currentUser')) {
            //console.log('User successfully authenticated...');
            return true;
        } else {
            // console.log('User is not authenticated...');
            return false;
        }
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');
        console.log('User successfully logged out');
    }
}

我能够成功登录控制台的用户名,所以我知道我已经捕获了这个值。我现在要做的是从" this.model.username"传递该值。到我的房间组件,目前看起来像这样:

import { ChatService } from './../chat/chat.service';
import { User } from './../../views/user/user';
import { Component, OnInit, Input } from '@angular/core';
import { AuthenticationService } from './../../data/authentication.service';
import { Http, Headers, Response } from '@angular/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-room',
  templateUrl: './room.component.html',
  styleUrls: ['./room.component.less']
})
export class RoomComponent implements OnInit {

  otherImg = 'app/img/photo-ph.png';
  // otherImg = 'app/img/portrait-place-holder.svg';
  model: any;
  loading = false;

  others = [
    { id: 1, name: 'John Smith', avatar: 'app/img/photo-ph.png' },
    { id: 2, name: 'Javier Sanchez', avatar: 'app/img/photo-ph.png' }
  ];

  user;
  token;
  name;
  nickname;

  constructor(private authenticationService: AuthenticationService,
              private router: Router,
              private http: Http,
              private chatService: ChatService) { }


  isLoggedIn() {
    this.loading = true;
    if (this.authenticationService.isAuthenticated()) {
      return true;
    }
  }

  gotoChat() {
    this.chatService.gotoChat(this.user);
  }

  ngOnInit() {
  }

}

此组件的视图循环访问用户(其他人)并显示每个"其他"的图标。用户。这是代码:

<div *ngIf="isLoggedIn()" class="others">
    <span *ngFor="let other of others"><i [ngClass]="'material-icons'" (click)="gotoChat()" [routerLink]="['/chat']">person</i></span>
    <a [routerLink]="['/login']">Logout</a>
</div>

此处的最终目标是让人们看到已登录的其他人,并能够与他们进行聊天。

我遇到的问题是如何将我在登录组件中捕获的值(this.model.username)传递给房间组件。

2 个答案:

答案 0 :(得分:1)

在AuthenticationService的登录方法中,您将用户对象存储在本地存储中,您还应将其存储在身份验证服务中,以便在将其注入组件时,您可以访问用户对象。 / p>

您需要在AuthenticationService中添加另一个名为getUsername的方法来获取用户名。

看起来像这样:

@Injectable()
export class AuthenticationService {
    private username: string;
    constructor(private http: Http) {}

    login(username: string, password: string) {
        return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let user = response.json();
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));

                    // store username
                    this.username = user.username;
                }
            });
    }

    getUsername(): string {
        return this.username;
    }

答案 1 :(得分:0)

在angular2中使用@input标记,这将有助于您在组件之间传递信息

请参阅此链接以了解

http://www.thoughtdelimited.org/thoughts/post.cfm/learning-angular-2-tour-of-heroes-tutorial-lesson-5