Javascript 角度2:将值从一个组件传递到另一个组件
我已成功为Angular 2应用程序实现了登录服务。我现在要做的是将登录用户的用户名从该组件提供给一个单独的组件,特别是聊天组件。这样,当他们与另一个用户聊天时,我可以显示用户名。对于如何在Angular 2中将这样的值从一个组件传递到另一个组件,我仍然有点模糊。以下是我的登录组件中的代码:Javascript 角度2:将值从一个组件传递到另一个组件,javascript,angular,typescript,Javascript,Angular,Typescript,我已成功为Angular 2应用程序实现了登录服务。我现在要做的是将登录用户的用户名从该组件提供给一个单独的组件,特别是聊天组件。这样,当他们与另一个用户聊天时,我可以显示用户名。对于如何在Angular 2中将这样的值从一个组件传递到另一个组件,我仍然有点模糊。以下是我的登录组件中的代码: import { AuthenticationService } from './../../data/authentication.service'; import { AlertService } fr
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');
}
}
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() {
}
}
@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;
}
我能够成功地使用用户名登录到控制台,因此我知道我正在捕获该值。我现在要做的是将该值从“this.model.username”传递到我的房间组件,该组件当前如下所示:
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');
}
}
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() {
}
}
@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;
}
此组件的视图在用户(其他用户)之间循环,并为每个“其他”用户显示一个图标。这是代码:
<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)传递到room组件。使用angular2中的@input标记这将帮助您在组件之间传递信息 请查看此链接以获取参考
在AuthenticationService的登录方法中,您将用户对象存储在本地存储器中,还应将其存储在AuthenticationService中,以便在将其注入组件时,您能够访问用户对象 您需要将另一个名为getUsername的方法添加到AuthenticationService以获取用户名 它看起来像这样:
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');
}
}
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() {
}
}
@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;
}
您可以在您的
AuthenticationService
中添加一个方法,该方法返回当前用户名,就像您在验证用户时返回的用户名一样?谢谢,但我有用户名,因为正如我所提到的,我能够console.log它。我的问题是如何将它从一个组件传递到另一个组件。@BKD同样的事情也适用。在您的组件中,而不是console.logging用户名,将其存储在变量中,然后将其传递给子/嵌套组件。您将尝试这样做。谢谢你,鲁道夫。