Предоставить asyn c конвейерные данные в шаблоне другому компоненту - PullRequest
0 голосов
/ 01 марта 2020

Я использую канал Angular asyn c, чтобы подписаться на наблюдаемое в шаблоне (фрагменты кода ниже). Учитывая этот код, я хотел бы представить notifications.length другому компоненту, в частности, родительскому компоненту, чтобы он знал о количестве. Каков наилучший способ сделать это?

tification.component. html

<div *ngIf="notifications$ | async as notifications;>
  <div class="notifications-header">
    <h2>New Notifications<span class="counter">({{notifications.length}})</span></h2>
  </div>
  <div *ngFor="let notification of notifications;" class="notification-list">
    <!-- do stuff -->
  </div>
</div>

messages.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable} from 'rxjs';
import { notification } from 'src/app/model/notification.model';
import { notificationService } from '../../service/notification.service';

@Component({
  selector: 'app-notifications',
  templateUrl: './notifications.component.html',
  styleUrls: ['./notifications.component.css']
})

export class notificationsComponent implements OnInit {
  notifications$: Observable<notification[]>;
  constructor(private notificationService: notificationService) {}
  ngOnInit() {
    this.notifications$ = this.notificationService.getNotificationList();
  }
}

messages.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Observer } from 'rxjs';
import { Notification } from '../model/notification.model';

const RESOURCE = 'http://localhost:3333/notifications';

@Injectable({
  providedIn: 'root'
})

export class NotificationService {

  constructor( private http: HttpClient ) {}

  getNotificationList(): Observable<Notification[]> {
    return this.http.get<Notification[]>(RESOURCE + '?status=unread');
  }

...