[英]Angular 4/5 issue with routing Subject between Angular components via Angular Services
我有一個帶有HTML click事件的父組件,該事件將clicked元素傳遞給component.ts文件上的方法,我希望將此click事件路由到Services,並制成一個新的Subject
,然后使用next()
方法,將主題傳遞給其他同級組件,然后將數據綁定到同級組件的HTML。
因此,此數據的路由將如下所示:
父組件(通過click事件) ->服務(通過父組件上的方法)->兄弟組件(通過Service)*
這是我的數據傳遞開始的地方:
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ApiService } from '../api.service';
@Component({
selector: 'app-contacts-list',
templateUrl: './contacts-list.component.html',
styleUrls: ['./contacts-list.component.scss']
})
export class ContactsListComponent implements OnInit {
sortedFavorites: any[] = [];
sortedContacts: any[] = [];
constructor (private _apiService: ApiService, private router: Router) {}
ngOnInit(){ this.getContacts()}
getContacts() {
this._apiService.getContacts()
.subscribe(
(contacts) => {
//Sort JSON Object Alphabetically
contacts.sort( (a, b) => {
if (a.name > b.name) return 1;
if (a.name < b.name) return -1;
return 0;
});
//Build new Sorted Arrays
contacts.forEach( (item) => {
if (item.isFavorite) {
this.sortedFavorites.push(item);
} else {
this.sortedContacts.push(item);
}
});
});
}
openFavorite($event, i) {<--HTML click event passing 'i' in as object clicked
let selectedFavorite = this.sortedFavorites[i];
this._apiService.openSelectedContact(selectedFavorite); <--passing said object into method connected to my services.ts file
this.router.navigate(['/details']);
};
}
我使用創建的openFavorite()
方法傳遞的數據正在工作,因為執行console.log(selectedFavorite)
記錄了要傳遞的期望結果。
然后談到服務
app.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiService {
//API URL
private url: string = 'assets/api/contacts.json';
//Create new Subject and assign to local variable
public newContactSubject = new Subject<any>();
//Initialize HttpClient for request
constructor(private _http: Http) { }
//Pull JSON data from REST API
getContacts(): Observable<any> {
return this._http.get(this.url)
.map((response: Response) => response.json());
}
openSelectedContact(data) {
this.newContactSubject.next(data); <---Where data should be passing in!
}
}
**現在,我希望我的其他組件從app.service接收數據。
import { Component, OnInit } from '@angular/core';
import { ContactsListComponent } from './app/contacts-list/contacts-list.component';
import { ApiService } from '../api.service';
@Component({
selector: 'app-contact-details',
templateUrl: './contact-details.component.html',
styleUrls: ['./contact-details.component.scss']
})
export class ContactDetailsComponent implements OnInit {
selectedContact: any[] = [];
error: string;
constructor(private _apiService: ApiService) { }
ngOnInit() { this.showContact() }
showContact() {
this._apiService.newContactSubject.subscribe(
data => this.selectedContact = data) <--Where the data should be showing up from services.ts file
console.log(this.selectedContact.name); <-- This is logging Undefined
}
}
我在這里會想念什么? 非常感謝!
嘗試這個:
showContact() {
this._apiService.newContactSubject.subscribe(
data => {
this.selectedContact = data;
console.log(this.selectedContact.name);
}
}
這兩行代碼(包括您的日志記錄)都在傳遞給訂閱的函數內。 每次發出一個項目時,它僅在回調函數中運行代碼。
另外,通常建議您將主題設為私有,並僅使用如下代碼將其公開為只讀:
private selectedMovieSource = new Subject<IMovie | null>();
selectedMovieChanges$ = this.selectedMovieSource.asObservable();
請注意,主題是私有的,並且可以觀察到的是使用單獨的屬性公開的。 這些組件然后訂閱該主題的公眾觀察。
首先,組件的sort方法永遠不會排序,因為您忽略了返回值。 如果您想處理排序,則應使用以下concatcts = contacts.sort(...)
我建議您使用另一種模式:
import { Component, OnInit } from '@angular/core';
import { ContactsListComponent } from './app/contacts-list/contacts-list.component';
import { ApiService } from '../api.service';
import { OnDestroy } from "@angular/core";
import { ISubscription } from "rxjs/Subscription";
@Component({
selector: 'app-contact-details',
templateUrl: './contact-details.component.html',
styleUrls: ['./contact-details.component.scss']
})
export class ContactDetailsComponent implements OnInit, OnDestroy {
selectedContact: any[] = [];
error: string;
private subscription: ISubscription;
constructor(private _apiService: ApiService) { }
ngOnInit() {
this.subscription = this._apiService.newContactSubject().subscribe(data => {
this.selectedContact = data;
console.log(this.selectedContact.name);
});
}
showContact() {
this._apiService.newContactSubject.subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
但我發現還有另一個問題:您已將selectedContact
定義為任何對象數組,然后您希望將值作為對象: this.selectedContact.name
我希望您可以解決此問題:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.