2017-09-07 49 views
1

我想在角度4組件之間傳遞數據。 我不想使用input \ output。在Homecomponent中的 我想將數據推入服務並在page2組件中我想從服務中獲取數據。 我只是看着可觀察的和主題的方式,我試圖實現它沒有成功。角度4傳遞組件之間的數據沒有輸入輸出

HomeComponent

import { ClientService } from './../clinet-service.service'; 
import { Component, OnInit } from '@angular/core'; 
@Component({ 
    selector: 'page-home', 
    template: 'pages/home/home.html', 
}) 
export class HomeComponent implements OnInit { 

    clients = ['john', 'jane'] 
    clientFound = false 

    // constructor(private navController: NavController) { } 
    constructor(private clientService: ClientService) { 

    } 

    openClient(client) { 
    } 
    ngOnInit() { 
    this.clientService.subject.next([ 
     { name: 'Harold', age: 35 } 
    ] 
    ); 

} 

} 

page2component

import { ClientService } from './../clinet-service.service'; 
import { Component } from '@angular/core'; 
@Component({ 
    selector: 'page-2', 
    template: '{{clients}}' 
}) 
export class Page2Component { 
    client:any; 

    constructor( private clientService: ClientService) { 

    } 

    ngOnInit(){ 
    debugger 
    let clients = this.clientService.observable.subscribe(clients => console.log(clients)); 
    } 
} 

clientService

import { Injectable, OnInit, OnDestroy } from '@angular/core'; 
import { Subject } from 'rxjs/Subject'; 
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 
import { Observable } from "rxjs/Observable"; 

@Injectable() 

export class ClientService { 
    subject: Subject<any> = new Subject<any>(); 
    observable: Observable<any> = this.subject.asObservable(); 


} 

其實我不喜歡執行的方式,因爲我努力使簡單的事情,例如推送數據服務並將其用於其他組件,但我無法做到這一點。

+0

是什麼我不知道什麼在第2頁 –

+0

你沒有得到在控制檯什麼? –

+0

錯誤 – Kyrsberg

回答

3

你不能這樣做,因爲你使它變得不必要的複雜。這裏是你應該怎麼做:

HomeComponent

ngOnInit() { 
    this.clientService.subject.next([{ 
     {name: 'Harold', age: 35 }, 
     {name: 'Kumar', age: 40 }, 
    }]); 
} 

page2Component

ngOnInit(){ 
    let clients = this.clientService.observable.subscribe(clients => console.log(clients)); 
} 

服務

export class ClientService { 

    subject: Subject<any> = new Subject<any>(); 
    observable: Observable<any> = this.subject.asObservable(); 

    constructor() {} 
} 
+0

我試圖在父項目和子項目中執行該操作,並且在父項目之前加載了子項,所以我決定以可觀察的方式執行此操作 –

+0

如果在此之後使用API​​(我猜測您的服務被嘲笑),那麼您不會有這個問題,因爲你不會設置你的客戶,但只是讓他們。要檢查這一點,可以直接在聲明客戶端變量的位置設置服務中的客戶端。 – trichetriche

+0

我試圖做你的方式我得到under –

1

您的HomeComponent裝飾已損壞。當您使用外部模板文件時,您需要使用templateUrl而不是template

錯誤

@Component({ 
    selector: 'page-home', 
    template: 'pages/home/home.html', 
}) 

正確

@Component({ 
    selector: 'page-home', 
    templateUrl: 'pages/home/home.html', 
}) 

https://angular.io/api/core/Component

+0

我特意寫了一個帶有url的文本 –