【问题标题】:Need to Reload Browser to See Changes in Angular需要重新加载浏览器才能看到 Angular 的变化
【发布时间】:2017-10-09 17:09:30
【问题描述】:

我正在通过 ng-bootstrap 模式添加我的数据,但我遇到了一个问题,因为当我单击添加按钮时,需要刷新它才能看到新添加的数据。当我成功添加产品时,我已经调用了 this.getMaterials(),但它仍然需要刷新才能看到新添加的数据

export class MaterialsListComponent implements OnInit {
  closeResult: string;
    materials: any;
    subscription: Subscription;

  constructor(private modalService: NgbModal, private materialsService: MaterialsService) { }

  ngOnInit() {
    this.getAllMaterials();
  }

  getAllMaterials() {
    this.subscription = this.materialsService.getAll()
        .subscribe(
          (data:any) => {
            this.materials = data;
            console.log(data);
          },
          error => {
           console.log(error);
          });
  }

  onCreateMaterial(form: NgForm){
    const name = form.value.name;
    const description = form.value.description;
    this.materialsService.addMaterial(name, description)
      .subscribe(
          data => {
            this.getAllMaterials();
            console.log(data);
          },
          error => {
             console.log(error);
          });
  }

  open(content) {
      this.modalService.open(content).result.then((result) => {
        this.closeResult = `Closed with: ${result}`;
      }, (reason) => {
        this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
      });
    }

    private getDismissReason(reason: any): string {
      if (reason === ModalDismissReasons.ESC) {
        return 'by pressing ESC';
      } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
        return 'by clicking on a backdrop';
      } else {
        return  `with: ${reason}`;
      }
    }

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

}

服务

export class MaterialsService {
  url = AppSettings;
  materials: any;

  constructor(private httpClient: HttpClient) {}

 getAll() {
    if(!this.materials) {
        this.materials = this.httpClient.get<any>(this.url)
                            .map((response => response))   
                            .publishReplay(1)
                            .refCount();

    }
    return this.materials;
  }

  addMaterial(name: string, description: string) {
    return this.httpClient
    .post(
       this.url, 
       JSON.stringify({ name, description})
    )
    .map((response: any) => {
         return response;
        });
  }

【问题讨论】:

标签: angular angular-services angular-forms


【解决方案1】:

我想你需要在模态关闭时调用 getAllMaterial()(假设用户通过打开的模态添加了一些材料)

open(content) {
      this.modalService.open(content).result.then((result) => {
        this.closeResult = `Closed with: ${result}`;
        this.getAllMaterials();
      }, (reason) => {
        this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
      });
}

【讨论】:

    【解决方案2】:

    我不知道你们的服务怎么样。

    所以在你的MaterialsService 中,你应该声明一个 BehaviorSubject 如下:

    import { Injectable } from '@angular/core'
    import { BehaviorSubject } from 'rxjs/BehaviorSubject'
    
    @Injectable()
    export class MaterialsService {
      materials: Observable<any[]> // any : your data type
      // store data
      private store: {
        materials: any[]
      };
      private _source: BehaviorSubject<any[]>;
    
      constructor(private http: Http) {
         this._source = <BehaviorSubject<any[]>>new BehaviorSubject([]);
         this.store = { materials: [] };
    
         this.materials = this._source.asObservable();
      }
    
      getAll() {
         this.http.get(`${this.baseUrl}/materials`).map(response => response.json())
           .subscribe(materials => {
             this.store.materials= materials;
    
             this._source.next(Object.assign({}, this.store).materials);
         }, error => console.log('Could not load materials.'));
      }
    
      addMaterial(name, description) {
         this.http.post(`${this.baseUrl}/materials`, JSON.stringify({name, description}))
          .map(response => response.json()).subscribe(data => {
             this.store.materials.push(data);
    
             this._source.next(Object.assign({}, this.store).materials);
         }, error => console.log('Could not add material.'));
      }
      ...
    }
    

    在您的 MaterialsListComponent 中,您订阅了一个 Observable:

    export class MaterialsListComponent implements OnInit {
      materials: Observable<any[]>;
    
      constructor(private modalService: NgbModal,
                  private materialsService: MaterialsService) { }
    
      ngOnInit() {
        this.materials = this.materialsService.materials;
      }
    }
    

    每当我们的 Observable Angular 发出一个新值时,都会更新视图。

    <!-- Async pipe is used to bind an observable directly in your template -->
    <div *ngFor="let item of materials | async">
      {{ item.name }}
    </div>
    

    希望对您有所帮助!

    【讨论】:

    • 我已经添加了我的服务。你能帮忙吗。谢谢
    • 你有没有尝试做一些改变作为我的回答?
    • 还没有。我把网址放在哪里?
    • 你通过你的网址改变${this.baseUrl}/materials
    • getAllMaterials 网址怎么样?我把它放在哪里?
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多