【问题标题】:Getting the value of a property in app.component获取 app.component 中属性的值
【发布时间】:2018-10-07 11:38:44
【问题描述】:

我知道这个问题与组件交互有关,谷歌搜索了解但我没有得到我所缺少的东西。

我想检查 app.component.html 中的属性值 在我的 Angular 应用中,

我有一个登录组件,它从用户那里获取输入值,例如用户名和密码。一旦用户通过身份验证,路由器就会绘制相应的布局。

我的尝试,

app.component.html(方法一)

<app-applayoutmodel></app-applayoutmodel>
<div class="container">
<router-outlet></router-outlet>
</div>

app-applayoutmodel 这个组件包括侧边导航和工具栏 layout 和 router-outlet 分别负责布局 单击侧导航中的导航项。

但是我想把html改成如下,(方法2)

<div *ngIf="user_name !== undefined">
<app-applayoutmodel></app-applayoutmodel>
</div>
<div class="container">
<router-outlet></router-outlet>
</div>

这里对于用户名,一旦用户输入表单并提交表单,我想从登录组件中获取值。

app.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  @Input() user_name: string;
}

和 login.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { User } from '../models/user';
import { LoginService } from '../../../serviceProviders/loginservice';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { AppComponent } from '../../app.component';

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

  user_name: string;
  password: string;
  public user: User;
  private errorMsg: string;


  constructor(private loginService: LoginService,
    private router: Router,
    public dialog: MatDialog) { }

  ngOnInit() {
  }

  userLogin() {
    console.log(this.user_name);
    this.loginService.signIn(this.user_name, this.password)
    .subscribe(
      data => {
        this.user = data;
        this.router.navigate(['/applayout']); },
      err  => {
        const dialogRef = this.dialog.open(DialogOverview, {
          width: '400px'
        });
        dialogRef.afterClosed().subscribe(result => {
          this.router.navigate(['/login']);
         // this.animal = result;
        });
        this.errorMsg = err;
      }
  );
  }
}
}

和 login.component.html

<div class="firstDiv"></div>
<div class="secondDiv"></div>
<div class="loginDiv">
  <form>
    <div class="row center">
      <i class="fa fa-user-circle"></i>
    </div>
    <div class="container">
      <input type="text" matInput placeholder="Username" type="text" name="username"  [(ngModel)]="user_name">
      <input type="password"  matInput placeholder="Password" name="password"  [(ngModel)]="password">
      <br/>
      <br/>
      <button mat-button (click)="userLogin()">Login</button>
      <br/>
      <label>
      <input type="checkbox" checked="checked" name="remember"> Remember me
    </label>
    </div>
  </form>
</div>

如果我在打开 login.component 时选择方法 1,则视图只会显示到工具栏的高度,如下所示,

这样,我无法继续登录。

我认为解决方案正在使用方法 2,因为最初加载应用程序时,app.component.html 中的 user_name 未定义,并且 app-appplayoutmodel 不会显示并且可以继续登录。

请帮帮我,如果上面的方法2正确,该怎么做。

这里是路由器路径,

const routes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: '', redirectTo: '/login', pathMatch: 'full'},
  {path: 'applayout', component: AppComponent}
];

【问题讨论】:

  • 我不确定我是否明白了您的要求。在您的 login.component 中,您获得了用户名和密码?您现在希望您的 app.component 知道用户名(和/或密码)吗?如果 login.component 是 app.component 的子级,则可以从 login.component 向 app.component 发出事件。是这样的吗?
  • 是的,但是我的组件之间没有父子关系,我当然想知道app.component中登录组件的用户名
  • 将用户名写入url并从路径中获取没有帮助?
  • @JoãoGhignatti,如何读取 app.component.ts 中的 url 参数?我现在可以将用户名作为 url 查询参数传递。
  • @Anil:这是从*.component.ts 读取URL 参数的方法:首先导入Router,然后在constructor 中获取它的实例,例如:public router: Router,然后@ 987654333@ 如果不需要,则不必使用parseUrl(),但如果需要,可以使用。

标签: angular angular-routing angular-components angular-router


【解决方案1】:

编辑 - 使用参数的新编辑
更好的解决方案是不将用户名作为查询参数,而是将其作为路由参数。

要实现所以你必须设置你的app.routes.ts:

export const mainRoutes: Routes = [
  { path: '', component: LogInComponent },
  { path: '/:userName', component: MainComponentAfterLogged }
];

用户填写表单登录后,您可以:

constructor(private _router: Router) {}

... inside method
this._router.navigate(['this.userName]);

对于您的主要组件,必须接收用户名的组件:

constructor(private _route: ActivatedRoute) {}

ngOnInit() {
    this._route.params.subscribe(
      params => this.userName = params['userName']
);

查询参数不太好

一种可能的解决方案是将用户名放在您的 URL 中并订阅您的应用程序内的路由更改。我认为这是解决您的问题的好方法,因为 app.component 在您更改路线时总是会更新。

您可以参考thisstackoverflow 的答案来正确路由。 类似于(在您的登录组件内):

import {Router} from '@angular/router';

userName: string;

constructor(private _router: Router) {}

// ... somewhere inside a method
this._router.navigate([ '', { name: userName } ]);

要订阅路线更改,您可以在 app.component.ts 中:

// Imports needed
import {ActivatedRoute} from '@angular/router';

private sub: any;
userName: string = '';

constructor(private _router: ActivatedRoute) {}

ngOnInit() {
  // Subscribe to active route changes
  this.sub = this.route.params.subscribe(params => {
    // Get the content of param 'name' everytime it changes
    this.userName = params['name'];
    // call a method or so to do something with that information
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多