首页 > 解决方案 > 第一次更新请求需要重新加载浏览器才能看到变化,但下一次更新请求不需要刷新浏览器才能看到变化

问题描述

第一个更新请求需要重新加载浏览器才能看到更改,但下一个更新请求不需要刷新浏览器才能看到更改。

//服务中的代码

    import { HttpClient } from "@angular/common/http";
import { EventEmitter, Injectable } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { BehaviorSubject, Observable, Subject } from "rxjs";
import { map, tap } from 'rxjs/operators';
import { environment } from "src/environments/environment";
import { User } from "../shared/user.model";

@Injectable({ providedIn: 'root' })
export class ContactService {
    users: User[] = [];
    populate = new EventEmitter();
    usersChanged: BehaviorSubject<User[]> = new BehaviorSubject([]);
    data: User = {
      name: '',
      email: '',
      contact: ''
    };
      
    constructor(private http: HttpClient, private route: ActivatedRoute) {}

    setValues(index: number) {
      console.log('Method Works');

      this.viewUser(index).subscribe((data) => {
        this.data.name = data.name;
        this.data.email = data.email;
        this.data.contact = data.contact;
        console.log(this.data.name);
      });
      

      this.populate.emit(this.data);
    }

    getValues() {
      return this.data;
    }

    getUsers() {
        return this.users.slice();
    }

    getUser(index: number) {
        return this.users[index];
    }

    updateUser(index: number, newUser: User) {
      console.log(index, newUser);
       return this.http.put<User>(`${environment.apiBaseUrl}/update/` + index, newUser);
    }

    deleteUser(index: number) {
      return this.http.delete(`${environment.apiBaseUrl}/delete/` + index)
    }

    setUsers(users: User[]) {
        this.users = users;
        this.usersChanged.next(this.users.slice());
      }

      viewUser(index: number): Observable<any> {
        return this.http.get<any>(`${environment.apiBaseUrl}/users/` + index)
      }

      fetchUsers(): Observable<User[]> {
            return this.http
          .get<User[]>(
            `${environment.apiBaseUrl}/users`
          )
          .pipe(
            map(users => {
              const usersArray: User[] = [];
              for (const key in users) {
                if (users.hasOwnProperty(key)) {
                  usersArray.push({ ...users[key] });
                }
              }
              return usersArray;
            }),
            tap(users => {
              this.setUsers(users);
            })
          )
        }

    createAndStorePost(user: User) {
        this.http.post<User>(`${environment.apiBaseUrl}/add`, user).subscribe((data:any) => {
          this.users.push(data);
        })
    }

}
    }

//CODE IN contact-list.component 这是在模板中显示来自 DB 的每个用户迭代的位置。

    import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { User } from '../shared/user.model';
import { ContactService } from './contact.service';

@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit, OnDestroy {
  users: User[] = [];
  subscription: Subscription;
  user: User;
  id: number;
  isFetching = false;
  usersSubscription: Subscription;
  
  @Output() populateFields = new EventEmitter();

  constructor(private router: Router, private route: ActivatedRoute, private contactService: ContactService) { }

  ngOnInit() {

    this.usersSubscription = this.contactService.fetchUsers().subscribe(data => {
      this.users = data;
      this.isFetching = true;
    }, error => { this.router.navigate(['bad-request'])});

    this.subscription = this.contactService.usersChanged.subscribe(
      (users: User[]) => {
        this.users = users;
      }
    );
  }


  onDelete(index: number) {
    this.contactService.deleteUser(index).subscribe((data: any) => {
      this.ngOnInit();
    }, error => { this.router.navigate(['bad-request']) });
  }

  onEdit(index: number) {
    this.router.navigate(['home/update', index]);
    this.contactService.setValues(index);
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
    this.usersSubscription.unsubscribe();
  }
}

//代码在form.component

      ngOnInit() {
    this.paramsSubscription = this.route.params.subscribe((params: Params) => {
      this.id = +params['id'];
      
          if (params['id'] != null) {
            this.editDetails();
            this.updateMode = params['id'] != null;
          } else {
            this.initForm();
          }
    });
  }

  onSubmit() {
    if (this.updateMode) {
      this.contactService.updateUser(this.id, this.signupForm.value).subscribe((data: User) => {
        console.log(data);
      }, error => { this.router.navigate(['bad-request']) });
    } else {
      this.contactService.createAndStorePost(this.signupForm.value);
    }
    this.onClear();
    this.router.navigate(['home']);
  }

谁能帮我这个?TIA。

标签: angular

解决方案


推荐阅读