2017-06-20 110 views
2

我試圖做一些角度項目,但我不進入網頁開發。其簡單的商店。
我想通過Play Framework從sqlite獲取一些信息。這是工作。

我收到它後,角度和顯示。 它的工作太。服務:從一個組件到另一個組件的訪問變量

@Injectable() 
export class ProductService { 

constructor(private http: Http) { } 

getProducts() { 
    const headers: Headers = new Headers(); 
    headers.append('Accept', 'application/json'); 
    headers.append('Content-Type', 'application/json'); 

    const options = new RequestOptions({headers: headers}); 

    return this.http.get('http://localhost:9900/', options) 
    .map(response => <Product[]>response.json()); 
} 
} 

和地點時,我把所有的產品:

export class ProductComponent implements OnInit { 

public products: Product[]; 
actualProduct: Product; 
productForm: FormGroup; 
public quantity: number; 
private activeFilter: string = "reset"; 
public allFilters: Array<string>; 


constructor(private productService: ProductService,private router:Router) { 
    this.allFilters = ['ocean', 'river', 'aquarium', 'reset']; 
} 

ngOnInit() { 
    this.productService.getProducts().subscribe(data => this.products = data); 
} 

public getActualProduct() { 
    return this.actualProduct; 
} 

clickedProduct(product) { 
    this.actualProduct = product; 
    let link = ['/detail', product.prodId]; 
    this.router.navigate(link); 
} 

public setFilter(filter: string) { 
this.activeFilter = filter; 
} 
} 

所以我的問題:我怎麼可以訪問陣列產品中的其他成分?因爲現在,當我點擊按鈕與功能clickedProduct其工作完美。它顯示在控制檯對象產品中。但是,當我嘗試使用產品的其他組件來顯示產品的詳細信息我失敗:

export class ProductDetailComponent implements OnInit { 

selectedProduct: Product; 
products: Product[]; 
quantity: number; 

constructor(
private productService:ProductService, 
private productComponent: ProductComponent, 
private route:ActivatedRoute, 
private location:Location, 
    // private cartStore: CartStore 
) { } 

ngOnInit() { 
    this.selectedProduct = this.productComponent.getActualProduct(); 
} 

addToCart(product) { 
    console.log(this.selectedProduct) 
    console.log(product) 
    //this.cartStore.addToCart(product, this.quantity || 1) 
} 

goBack() { 
    this.location.back() 
} 
} 

我怎樣才能actualProduct變量ProductDetailComponent,不然我怎麼能得到的所有產品陣列? 我嘗試在productComponent中使用「@Input()actualProduct:Product」,但它實際上不起作用。 感謝您的幫助。

+0

看看是否有部件之間的父子關係?或者他們呈現在不同的路線? –

+0

如果您的問題是關於Angular的,請添加角標籤。 – 2017-06-20 07:43:25

回答

1

這與這些組件相互關聯的方式密切相關。

如果有親子關係,您可以通過使用@Input屬性信息傳遞到子組件,並通過@Output性手段聽父孩子的事件。

如果犯規存在組件之間這樣的關係(例如路由組件),那麼最普遍的選擇是創建一個服務管理組件之間的信息和/事件流中。

對於furhter信息,請參加the docs

+0

它們呈現在兩條不同的路線中。我現在明白,爲什麼我不能使用@Input(),因爲我嘗試過。創建服務只是爲了傳遞一個數組嗎?因爲這實際上是我所需要的。 – Shrike

+0

是的,你需要在服務中封裝該數組,並提供更新,重置和獲取它的函數。 Check this section https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service –

+0

謝謝!我會盡力做到這一點;) – Shrike

相關問題