Subject is not updating the component. I have 2 components c1 and c2 and a service class CommonService
C1 component having code related to post data.
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)
})
}
C2 component having code related to get data from API server.
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))
}
}
My C2 component is not updating automatically without page refresh, when C1 component inserts the data using POST call.
My Service File
@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)
}
}
Templates
Template: C1
<form>
<input type="text" #name />
<input type="submit" (click)="getData($event, name.value)" />
</form>
Template of C2:
<div *ngFor="let n of data">
{{ n.todo }}
</div>
Note: With refresh, the data is getting populated, but without refresh it is not working.
question from:
https://stackoverflow.com/questions/65861475/angular-subject-is-not-updating-the-component 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…