簡體   English   中英

如何將json對象的一個​​組件傳遞給angular中的另一個組件?

[英]How to pass json object one component to another component in angular?

如何將JSON對象從一個組件傳遞到另一個組件。 我有兩個組件LoginView和ProfileView。 我在LoginView組件中獲得了特定的用戶詳細信息。 我想將this.resultthis.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM