Display username of user who logs in (Angular 2)

2019-09-10 09:31发布

问题:

This seems like a very simple question but I'm new to Angular2 and I'm a bit confused by the relationship between components. I have a login page and when the user enters their username, I want the username to display on the dashboard, something like "Welcome, James".

I have a login.html page, a loginHTMLcomponent that has a templateurl to the login.html page and its parent which login.ts. I have dashboard.ts which is a parent of dashboard.component.ts which (has the HTML for the dashboard page)

Basically how do I get the username from the input field in login.html to appear in dashboard.component.html...I've probably explained this awfully. Thanks.

I'll try explain it a bit clearer In my login.html I have something like:

input type = "text" [(ngModel="name")]

And in my dashboard.component.ts, inside in my selector I would have:

@Component({
    selector: 'dashboardHTML',
    template:
    `
    <body>
      ........
      ..........
      <span ="user">Welcome, {{user}}</span>
      ...
      `

Update: Just wondering is the correct way in approaching using a service. In my login.component.html I have:

 <input id="username" type="text" class="form-control" 
placeholder="Username" ngControl="username" [(ngModel)]="name">

In my login.HTMLComponent(which has a templateURL to login.component.html) I have export class LoginHTMLComponent{ public name: {}; /////

And in my name.service.ts I have this

import { Injectable } from '@angular/core';
import {LoginHTMLComponent} from "./LoginComponents/login.HTMLcomponent";
@Injectable()
export class NameService {
    getName(){
        return name;
             }
}

I'm not sure if I'm calling name correctly here. Thanks

回答1:

Instead of trying to pass the username from the login component to the dashboard component, you should obtain it rather via a common service. The username is probably part of the response from the backend that logs your user in. That response, i.e. the logged-in user, is stored in a service, that can be injected into each of your components.

Services are often a good idea to exchange data between components that are not within a parent/child hierarchy.

https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

Regarding your service

The service should not have a reference to the LoginHTMLComponent or any other component. Inject the NameService in the constructor of your LoginComponent (and DashboardComponent) like this

private constructor(private nameService:NameService) {...}

and, of course, import the NameService.



回答2:

In your case a service might be good option. Store the login data in the service and access it from whichever component needs the data. Decorate the service with @Injectable() and then inject it into your components.