繁体   English   中英

通过Angular Services在Angular组件之间路由Subject的Angular 4/5问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM