gpt4 book ai didi

javascript - 了解为什么这个导入变量的字符串插值在我的 Angular 2 应用程序中起作用

转载 作者:太空狗 更新时间:2023-10-29 19:29:59 25 4
gpt4 key购买 nike

在对我的 Angular 2 应用程序进行一些编辑时,我能够在我认为它应该工作之前让一些东西工作。换句话说,我有点困惑为什么它在当前配置下工作。具体来说,我有一个 authentication.service 来处理我的登录身份验证。我有一个登录组件和一个聊天组件,它们在各自的构造函数中都有一个 authentication.service 的私有(private)实例。我想要做的是能够将用户名从登录功能向下传递到聊天 View ,这样我就可以在聊天框中显示登录用户的用户名。我已经开始工作了,但是,奇怪的是,我通过添加“this.authenticationService.username = this.model.username;”来让它工作。在 login.component 中,而不是在 authentication.service 中。所以我对 chat.component 如何/为什么甚至可以访问该信息感到困惑。如果我从 login.component 中删除那一行代码,用户名将不会传递到 chat.component。但是我从来没有真正将登录组件导入到聊天组件中,那么它是如何工作的呢?很想知道是否有人可以帮助我理解这一点。这是有问题的文件。首先,我的 authentication.service 文件:

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 {

username;

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');
}
}

这是我的 login.component 文件:

import { UserService } from './../../data/user.service';
import { AuthenticationService } from './../../data/authentication.service';
import { AlertService } from './../../data/alert.service';
import { Component, OnInit, Input } 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 {

model: any = {};
loading = false;
username;
password;

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

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;
});
this.authenticationService.username = this.model.username;
}

}

这是我的 chat.component 文件:

import { AuthenticationService } from './../../data/authentication.service';
import { Router, ActivatedRoute } from '@angular/router';
import { ChatService } from './chat.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { TabPage } from '../../ui/tab-navigation/tab-page';

@Component({
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.less'],
})
export class ChatComponent extends TabPage implements OnInit, OnDestroy {

messages = [];
users = [];
routes;
connection;
userbase;
route;
message;
user;

constructor(private chatService:ChatService,
router: Router,
route: ActivatedRoute,
private authenticationService: AuthenticationService) {

super(router, route);

this._title = 'Chat Room';

this.addEventListener('paramsChange', function(params) {

this._title = 'Chat Room';

}.bind(this));
}

sendMessage() {
this.chatService.sendMessage(this.message);
this.message = '';
}

sendUser() {
this.chatService.sendUser(this.user);
this.user = '';
}

trackUser() {
this.chatService.trackUser(this.route);
console.log('A user just navigated to ' + this.route);
}

// For when user clicks "enter/return" to send message
eventHandler(event: KeyboardEvent): void {
if (event.key === 'Enter') {
this.chatService.sendMessage(this.message);
this.message = '';
}
}

ngOnInit() {
this.connection = this.chatService.getMessages().subscribe(message => {
this.messages.push(message);
});
this.userbase = this.chatService.getUsers().subscribe(user => {
this.users.push(user);
});
this.routes = this.chatService.getRoutes().subscribe(route => {
this.routes.push(route);
});
}

ngOnDestroy() {
this.connection.unsubscribe();
this.userbase.unsubscribe();
}

public getTabId(params): string {
return 'Chat Room';
}
}

最后,我的 chat.component.html 文件如下所示(这是我实际使用字符串插值在聊天中显示用户名的地方):

<div class="centered-display" align="center">
<h3>User: {{authenticationService.username}}</h3>
<div *ngFor="let message of messages" class="message">
{{authenticationService.username}}: {{message.text}}
</div>
<input class="form-group" [(ngModel)]="message" (keypress)="eventHandler($event)">
<div class="spacing">
<button class="submit-btn" md-button (click)="sendMessage()">SEND</button>
</div>
</div>

有人可以帮助我理解为什么它会按原样工作吗?使这项工作起作用的一行是我的 login.component 登录函数中的最后一行:“this.authenticationService.username = this.model.username;”。但是,同样,我的聊天组件无法访问我的登录组件(据我所知)。那为什么会这样呢?

最佳答案

您的聊天组件和登录组件可能彼此不直接相关,但它们确实都可以访问 authenticationService .具体来说,它们都引用了注入(inject)的该服务的同一实例。

这意味着当你做 this.authenticationService.username = this.model.username在您的登录组件中,您在相同的 authenticationService 上设置用户名属性您正在通过聊天组件 View ( {{authenticationService.username}}) 中的插值访问的对象。

关于javascript - 了解为什么这个导入变量的字符串插值在我的 Angular 2 应用程序中起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com