[英]How to pass json object one component to another component in angular?
如何将JSON
对象从一个组件传递到另一个组件。 我有两个组件LoginView和ProfileView。 我在LoginView组件中获得了特定的用户详细信息。 我想将this.result
和this.studentresult
传递给ProfileView组件,基本上在登录后,我试图将用户详细信息传递给用户个人资料页面。 我该怎么做,帮帮我,我是新手。
但就我而言,我想在LoginView组件中调用3个api,并且我需要将所有这些api结果传递给ProfileView组件
LoginView组件
export class LoginView {
constructor(private http: HttpClient, private router: Router) {}
ngOnInit() {}
this.http.get('http://localhost:8080/user/1')
.subscribe((response: any) => {
this.result = response;
}
}
this.http.get('http://localhost:8080/student/1')
.subscribe((response: any) => {
this.studentresult = response;
}
}
}
ProfileView组件
export class ProfileView {
constructor() { }
ngOnInit() {}
}
您可以创建共享服务,在LoginView上设置一个变量,然后在ProfileView上读取它。
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService{
userData;
constructor(){
this.userData= {};
}
setUserData(val: object){
this.userData= val;
}
getUserData(){
return this.userData;
}
}
LoginView组件
export class LoginView {
constructor(private http: HttpClient, private router: Router, private sharedService: SharedService) { }
ngOnInit() {
}
this.http.get('http://localhost:8080/user/1')
.subscribe((response:any) => {
this.result = response;
this.sharedService.setUserData(response);
}
}
ProfileView组件
export class ProfileView {
constructor(sharedService: SharedService) {
console.log(sharedService.getUserData());
}
ngOnInit() {}
}
将Observable.forkJoin
用于您的请求,然后使用共享服务在组件之间传递数据。 我喜欢使用BehaviorSubjects
在不相关的组件之间共享数据。
服务:
// behaviorsubject wants an inital value
private mySubject = new BehaviorSubject([]);
public mySubject$ = this.mySubject.asObservable();
setValue(value) {
this.mySubject.next(value);
}
在模块级别而非组件级别提供此服务。
然后如前所述,使用Observable forkjoin并行执行请求。 这将产生结果数组,并按您提供的顺序提供内容,您可以通过服务将其传递给其他组件:
(案例:不使用管道运算符):
let user = this.http.get('http://localhost:8080/user/1');
let student = this.http.get('http://localhost:8080/student/1');
Observable.forkJoin([user, student]).subscribe(data => {
this.myService.setValue(data);
});
然后,在您的其他组件中,您订阅可观察对象:
this.myService.mySubject$.subscribe(data => {
this.user = data[0];
this.student = data[1];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.