我有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 { }
謝謝
您已經發布了兩次類別組件,而不是您的類別服務 – Steveland83
還請提供父模塊 - 需要聲明兩個組件並提供服務以便在組件之間共享相同的服務實例。 – Steveland83
@ Steveland83我已經糾正了它 – user3701188