角度中的主题和可观察

时间:2020-08-06 09:24:36

标签: angular typescript observable

我正在学习有角度的知识,我对可观察的主题有些困惑。 我有一项服务,该服务会在应用加载时首先从http请求发出一个字符串数组,并且它只会发出存储的数据。

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class Service1Service {

  persons: string[];
  pesonChanged = new Subject<string[]>();
  isFirst= true;

  fetchPersons() {
    if(this.isFirst){
      this.http.get<any>('https://swapi.dev/api/people')
      .pipe(map(resData => {
        return resData.results.map(character => character.name);
      }))
      .subscribe(transformedData => {
        this.persons = transformedData;
        this.pesonChanged.next(transformedData);
      });
      this.isFirst = false;
    } else {
        this.pesonChanged.next(this.persons);
    }
  }

  addPerson(name: string) {
    this.persons.push(name);
    this.pesonChanged.next(this.persons);
  }

  removePerson(name: string){
    this.persons = this.persons.filter(person => {
      return person !== name;
    });
    this.pesonChanged.next(this.persons);
  }
  constructor(
    private http: HttpClient
  ) { }
}

我的观察者第一次接收到数据,但是第二次什么都没看到,subscribe方法将不会获取我的数据。

import { Service1Service } from './service1.service';
import { Component, OnInit, Output, EventEmitter, OnChanges, OnDestroy } from '@angular/core';
import { Input, ChangeDetectorRef, SimpleChanges } from '@angular/core';
import { HttpRequest, HttpClient } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { animation, transition } from '@angular/animations';
import { trigger, state, style, animate } from '@angular/animations';
import { Subscription } from 'rxjs';
import { timeout } from 'rxjs/operators';



@Component({
  selector: 'app-mdl',
  template: `
    <p *ngIf="isFetching">Loading...</p>
    <ul *ngIf="!isFetching">
      <li *ngFor="let p of personList" (click)="onRemove(p)">
        {{p}}
      </li>
    </ul>

  `,
  styles: [
  ],
  styleUrls: ['./animated-button.component.css'],
  animations: [

  ]
})
export class MdlComponent implements OnInit, OnChanges, OnDestroy{
personList: string[];
personListSubs: Subscription;
isFetching = true;
prova: any;

constructor(
  private myService: Service1Service
) {
}
ngOnInit(): void {
  if(this.myService.isFirst){
    this.myService.fetchPersons();
    this.personListSubs = this.myService.pesonChanged.subscribe(persons => {
      this.personList = persons;
      this.isFetching = false;
    });
  } else {
    this.myService.fetchPersons();
    this.personListSubs = this.myService.pesonChanged.subscribe(persons => {
      this.personList = persons;
      this.isFetching = false;
    });
  }
}
onRemove(p: string) {
  this.myService.removePerson(p);
}
ngOnChanges(changes: SimpleChanges): void {
}
ngOnDestroy() {
  this.personListSubs.unsubscribe();
}
}

我在做什么错了?

0 个答案:

没有答案