2017-08-10 128 views
1

我有2個組件。 CategoryComponent和CategoryProductComponent。我還有CartegoryService服務。 CategoryComponent返回一個表,其中包含從我的CategoryService中獲取的類別列表。在表格的每一行上都有一個按鈕,當點擊該按鈕時,將您從CategoryComponent轉到CategoryProductComponent,它將向您顯示該類別中的產品列表。組件之間的角度溝通

從我的API時,我得到的JSON,我有聯繫陣列上的rel =類別的產品,並有完整的鏈接一個href來獲取相關產品。

現在的問題是,當我在CategoryComponent中獲取json,並且當用戶單擊鏈接查看產品列表時,我得到該鏈接,然後調用CategoryService中的方法,然後將其分配給一個變量我將route.navigate稱爲CategoryProductComponent,它現在會在鏈接被分配後提取產品列表。

這時候我把網址手動在瀏覽器不工作,然後COS鏈接不是從CategoryComponent fectched。我讀過服務是單身人士,所以我想這個變量至少會在第一次分配後保持填充狀態。 我可以在我的組件之間進行這種通信的最佳方式。

而且我可以通過鏈接作爲router.navigate一個額外的對象,但我沒有看到這是理想特別是當人們決定直接在瀏覽器中輸入URL。

category.component.ts

import { Category, FinalCategoryResponse, CategoryResponse, Link } from './category'; 
import { CategoryService } from './category.service'; 
import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { Router } from '@angular/router'; 
import {Observable} from 'rxjs/Rx'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Component({ 
    selector: 'app-category', 
    templateUrl: './category.component.html', 
    styleUrls: ['./category.component.css'] 
}) 
export class CategoryComponent implements OnInit, OnDestroy { 

    categories: Category[]; 
    categoryResponses: CategoryResponse[]; 
    constructor(private categoryService: CategoryService, private router: Router) { } 

    ngOnInit() { 
    this.categoryService.getCategories() 
     .subscribe(responseCategories => this.categoryResponses = responseCategories 
     , (err) => { 
     if (err.error instanceof Error) { 
     // A client-side or network error occurred. Handle it accordingly. 
     console.log('An error occurred:', err.error.message); 
     } else { 
     // The backend returned an unsuccessful response code. 
     // The response body may contain clues as to what went wrong, 
     console.log(`Backend returned code ${err.status}, body was: ${err.error}`); 
     } 
    }); 
    } 

    showCategoryProducts(categoryResponse: CategoryResponse , relName: string) { 
    const links: Link[] = categoryResponse.links; 
     for (const link of links) { 
     if (link.rel === relName) { 
      this.categoryService.assignCategoryProductLink(link.href); 
      this.router.navigate(['/categories', categoryResponse.category.id, 'products']); 
     } 
     } 
    } 


    ngOnDestroy(): void { 
     // unsubscribe to all subscriptions here 
     } 
} 

類別-service.ts

 import { Product } from '../product/product'; 
import { Category, FinalCategoryResponse, CategoryResponse } from './category'; 
import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 

@Injectable() 
export class CategoryService { 

    private categoryProductLink: string; 
    constructor(private http: Http) { } 

    getCategories() { 
    return this.http.get('http://localhost:8080/api/categories') 
     .map(response => <CategoryResponse[]>response.json()); 
    } 

    assignCategoryProductLink(link: string) { 
    this.categoryProductLink = link; 
    } 

    getCategoryProducts() { 
    return this.http.get(this.categoryProductLink) 
     .map(response => <Product[]>response.json()); 
    } 
} 

類別-product.component.ts

import { Product } from '../../product/product'; 
import { CategoryService } from '../category.service'; 
import { Component, OnInit, OnDestroy } from '@angular/core'; 

@Component({ 
    selector: 'app-category-product', 
templateUrl: './category.product-component.html', 
    styles: [] 
}) 
export class CategoryProductComponent implements OnInit, OnDestroy { 

    products: Product[]; 
    constructor(private categoryService: CategoryService) { } 

    ngOnInit() { 
    this.categoryService.getCategoryProducts() 
    .subscribe(results => this.products = results); 
    } 


ngOnDestroy(): void { 

    } 
} 

category.module

import { CategoryComponent } from './category.component'; 
import { CategoryService } from './category.service'; 
import { NgModule } from '@angular/core'; 
import { CommonModule } from '@angular/common'; 
import { CategoryProductComponent } from './category-product/category-product.component'; 
import { CategoryRoutingModule } from './category-routing.module'; 
import { AddCategoryComponent } from './add-category/add-category.component'; 
import { ReactiveFormsModule } from '@angular/forms'; 

@NgModule({ 
    imports: [ 
    CommonModule, 
    CategoryRoutingModule, 
    ReactiveFormsModule 
    ], 
    declarations: [ 
    CategoryComponent, 
    CategoryProductComponent, 
    AddCategoryComponent 
    ], 
    exports : [CategoryComponent, CategoryProductComponent, AddCategoryComponent], 

    providers : [CategoryService] 
}) 
export class CategoryModule { } 

謝謝

+0

您已經發布了兩次類別組件,而不是您的類別服務 – Steveland83

+0

還請提供父模塊 - 需要聲明兩個組件並提供服務以便在組件之間共享相同的服務實例。 – Steveland83

+0

@ Steveland83我已經糾正了它 – user3701188

回答

2

我沒有發現這一點,當我第一次看到你的問題。

這時候我把網址手動在瀏覽器中

使用角路由器不工作維護您的應用程序的狀態,因爲你沒有實際航行的任何地方,當你使用它,但手動輸入鏈接到您的瀏覽器意味着您深入鏈接到您的應用程序 - 我相當確定它失去了以前的任何狀態,因爲您正在有效地重新啓動應用程序。

附註 - 我很驚訝,這是一個問題給你,當然這是預期的行爲?

如果你真的想爲這個要求,那麼在CategoryService你可以localstorage存儲數據如下:

setCategoryProductLink(link: string) { 
    localStorage.setItem('categoryProductLink', link); 
    } 

    getCategoryProductLink(): string { 
    return localStorage.getItem('categoryProductLink'); 
    } 

這將持續它的會話之間。

+0

我明白這是預期的行爲,因爲它並沒有首先進入CategoryComponent,它沒有鏈接從服務中獲取產品。 使用本地存儲意味着我將不得不至少一次。我無法直接進入categoryproductLink頁面,而無需進入分類頁面。 還有一個產品列表,每一次點擊都會給出一個新的鏈接。 我可以做到這一點的另一種方式是不使用相關的鏈接,而只是從url瀏覽器獲取id並相應地進行提取。但後來我沒有機會使用我的rel鏈接。 – user3701188

+0

我所要求的是一種使用我的組件之間的rel鏈接的方式 – user3701188

+0

爲什麼不把url + localstorage方法結合起來。因此,在您的服務中,首先檢查是否存在匹配的路由參數,如果沒有,則查看localstorage。如果我理解正確,我認爲這將處理您的兩項要求。 – Steveland83