我有一个带有 HTML 单击事件的父组件,该事件将单击的元素传递给 component.ts 文件上的方法,我希望将此单击事件路由到服务,使其成为一个新的 Subject
,然后使用 next()
方法,将主题传递给不同的同级组件,并将数据绑定(bind)到同级组件的 HTML。
因此该数据的路由将如下所示:
父组件(通过点击事件) --> 服务(通过父组件上的方法)--> 兄弟组件(通过服务)*
这是我的数据传递开始的地方:
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)
记录了要传递的所需结果。
然后转向服务
应用程序.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),并且仅使用如下代码公开它的只读可观察对象:
private selectedMovieSource = new Subject<IMovie | null>();
selectedMovieChanges$ = this.selectedMovieSource.asObservable();
请注意,主题是私有(private)的,并且它的可观察对象是使用单独的属性公开的。然后,组件订阅主题的公共(public)可观察对象。
关于javascript - 通过 Angular 服务在 Angular 组件之间路由主题的 Angular 4/5 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49339137/