我正在使用Angular9。在登录事件中,我需要将凭据从子级(登录组件)传递给父级(安全组件)。
在登录组件中,提交表单后,会触发一个事件:
@Output() changed = new EventEmitter<string>();
this.changed.emit('changed!!');
我想在父安全组件中订阅该事件。因此,我尝试以下操作:
this.subscription = this.loginComponent.getLoginDataChangeEmitter()
.subscribe(
item => console.log('subscribed', item)
);
问题在于console.log('subscribed', item)
从未被调用。
问题
我如何订阅this.changed.emit('changed!!');
?
更多信息
我有以下内容:
security.component.html (具有子级登录指令)
<p>Security Component</p>
<h2>{{response}}</h2>
<app-login></app-login>
security.component.html
import { Component, OnInit } from '@angular/core';
import { JwtClientService } from '../jwt-client.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { LoginComponent } from '../login/login.component';
@Component({
selector: 'app-security',
templateUrl: './security.component.html',
styleUrls: ['./security.component.css']
})
export class SecurityComponent implements OnInit {
loginData:any;
response:any;
subscription: any;
constructor(private service: JwtClientService, private router: Router, private route: ActivatedRoute, private loginComponent: LoginComponent) { }
ngOnInit(): void {
console.log('SecurityComponent ngOnInit', this.loginData);
console.log(this.route.snapshot.params);
this.subscription = this.loginComponent.getLoginDataChangeEmitter()
.subscribe(
item => console.log('subscribed', item)
);
if (!this.loginData) {
//this.router.navigate(['login', {}]);
} else {
this.getAccessToken(this.loginData);
}
}
public getAccessToken(loginData) {
let resp = this.service.generateToken(loginData);
resp.subscribe(data => {
let jsonData:string = JSON.parse(data.toString());
const token = jsonData['jwt'];
this.accessApi(token);
});
}
public accessApi(token) {
let resp = this.service.hello(token);
resp.subscribe(data => {
this.response = data;
});
}
}
login.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
@Output() changed = new EventEmitter<string>();
loginData: any = {};
constructor(private router: Router) {
}
ngOnInit(): void {
console.log('LoginComponent ngOnInit');
}
onSubmit(loginData: any) {
this.loginData = loginData;
console.log('Your order has been submitted', this.loginData);
this.changed.emit('changed!!');
//this.router.navigate(['auth']);
}
getLoginDataChangeEmitter() {
console.log('LoginComponent.getLoginData()');
return this.changed;
}
}
答案 0 :(得分:1)
您需要在父级中使用该输出参数:
security.component.html
<p>Security Component</p>
<h2>{{response}}</h2>
<app-login (changed)="handleChange($event)"></app-login>
security.component.ts
handleChange(val) {
console.log(val);
}