要在Angular 8中实现这个功能,你需要进行以下步骤:
// login.component.html
// login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
username: string;
constructor(private router: Router) {}
login() {
// 导航到下一个页面,并将用户名作为参数传递
this.router.navigate(['/next'], { queryParams: { username: this.username } });
}
}
ActivatedRoute服务来获取URL参数,并订阅参数的变化。// navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
username: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// 订阅URL参数的变化
this.route.queryParams.subscribe(params => {
this.username = params.username;
});
}
}
这样,在用户点击登录按钮后,会导航到下一个页面,并在导航栏组件中显示用户名。