Angular:主题未更新组件

问题描述

主题未更新组件。我有 2 个组件 c1c2一个服务类 CommonService

具有与发布数据相关的代码的 C1 组件。

export class C1Component implements OnInit {
  dBservice: CommonService
  constructor(private service: CommonService) { 
    this.dBservice = service
  }
  ngOnInit(): void {
    
  }
  getData(event,val) {
    event.preventDefault();
    this.SendDataToServer(val)
  }

  SendDataToServer(value) {
    this.dBservice.postData(value).subscribe(data => {
      console.log(data)
    },err => {
        console.log(err)
    })
  }

具有与从 API 服务器获取数据相关的代码的 C2 组件。

  dBservice: CommonService
  data: []
  constructor(private service: CommonService) { 
    this.dBservice = service
  }

  ngOnInit(): void {
    console.log("coming")
    this.dBservice._updates.subscribe((data) => {
      console.log("c")
      this.dBservice.getAll().subscribe(data => console.log(this.data=data))
    })
    this.dBservice.getAll().subscribe(data => console.log(this.data=data))
  }

}

当 C1 组件使用 POST 调用插入数据时,我的 C2 组件不会在没有页面刷新的情况下自动更新。

我的服务文件

@Injectable({
  providedIn: 'root'
})
export class CommonService {
  updates : any;
  constructor(private http: HttpClient) {
    this.updates = new Subject<string>();
   }
  
  get _updates() {
    return this.updates;
  }
  postData(value) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',Authorization: 'my-auth-token'
      })
    };
    var url = "http://localhost:3000/Todos"
    return this.http.post<{ "todo": string }>(url,{
      "id" : uuid.v4(),"todo" : value
    },httpOptions).pipe(
      tap(() => {
        this.updates.next()
      })
    )
  }

  getAll() {
    var url = "http://localhost:3000/Todos"
    return this.http.get<[]>(url)
  }
}

模板 模板:C1

<form>
  <input type="text" #name />
  <input type="submit" (click)="getData($event,name.value)" />
</form>

C2 模板:

<div *ngFor="let n of data">
  {{ n.todo }}
</div>

注意:刷新后,数据会被填充,但没有刷新则无法工作。

解决方法

这是一个简化的示例,它在没有真正后端的情况下完成了非常相似的工作。它演示了 BehaviorSubject 的使用以及一个组件如何更新而另一个组件如何实时侦听和反应(完整的工作示例 here)。

服务

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Injectable()
export class DataService {
  updates$ = new BehaviorSubject<string[]>([]);

  constructor() {}

  postData(value: string): void {
    this.updates$.value.push(value);
    this.updates$.next([...this.updates$.value]);
  }
}

组件 1(发布组件):

HTML

<form>
  <input type="text" #name>
  <input type="submit" value="Post" (click)="submit($event,name.value)">
</form>

TS

import { Component,OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-posting',templateUrl: './posting.component.html',styleUrls: ['./posting.component.css']
})
export class PostingComponent implements OnInit {

  constructor(private dataService: DataService) { }

  ngOnInit() {
  }

  submit(event: Event,value: string): void {
    event.preventDefault();
    this.dataService.postData(value);
  }
}

组件 2(侦听器)

HTML

<ul>
  <li *ngFor="let value of updates">{{ value }}</li>
</ul>

TS

import { Component,OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-listing',templateUrl: './listing.component.html',styleUrls: ['./listing.component.css']
})
export class ListingComponent implements OnInit {
  updates: string[] = [];

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.updates$.subscribe(updates => this.updates = [...updates]);
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...