【问题标题】:angular 2 view is not refreshed角度 2 视图未刷新
【发布时间】:2017-03-23 08:50:50
【问题描述】:

主书组件代码(book.component.ts)

import { Component, OnInit } from '@angular/core';
import { BookService } from './../app/book.service';
import { Observable } from 'rxjs/observable';
import 'rxjs/Rx';
import { Book } from './../app/Book';

@Component({
    selector: 'book',
    moduleId: module.id,
    templateUrl: 'book.component.html',
    providers: [BookService],
})

export class BookComponent {
    books: Book[];

    constructor(private bookService: BookService) {
        this.bookService.getBooks()
            .subscribe(books => {
                this.books = books;
            });
    }
    removeBook(id: number) {
        var books = this.books;
        this.bookService.removeBook(id).subscribe(data => {
            if (data.n == 1) {
                for (var i = 0; i < books.length; i++) {
                    if (books[i].id == id) {
                        books.splice(i, 1);
                    }
                }
            }
        });
    }
}

服务页面(book.service.ts)

import { Injectable } from '@angular/core';
import { Http,Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BookService{
    constructor(private http: Http){
        console.log('BookService Started....')
    }

    headers:string;

    getBooks(){
        return this.http.get('/api/books').map(res => res.json());
    }

    removeBook(id: number){
        return this.http.delete('/api/book/'+ id).map(res => res.json());
    }
}

书籍组件html代码(book.component.html)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="main.css">
    <base href="/">
    <title> Books </title>
</head>
<body>
    <nav class="navbar navbar-inverse bg-inverse navbar-fixed-top">
        <div class="container">
            <p id="book">BOOKS</p>
        </div>
    </nav><br><br><br>
    <div class="container">
        <div class="row">
            <div class="col-md-4">
                <div class="card card-1">
                    <h1> ADD </h1>
                </div>
                <div class="card card-2">
                    <h2><i class="material-icons">add_circle</i> ADD </h2>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card card-1">
                    <h1> SEARCH </h1>
                </div>
                <div class="card card-2">
                    <div class="block2">
                        <input class="inner" type="text" placeholder="Enter id"> <button class="btn btn-sm inner" type="button"><span>Search</span></button>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card card-1">
                    <h1> LIST </h1>
                </div><br>
                <div *ngFor="let book of books">
                    <div class="card card-2" (click)="removeBook(book.id)">
                        <font color="#212121" size="3px"> <b> ID </b> </font> : {{book.id}} <br>
                        <font color="#212121" size="3px"> <b> NAME </b> </font>: {{book.name}}<br>
                        <font color="#212121" size="3px"> <b> AUTHOR </b></font>: {{book.author}}
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</html>

当我单击删除时,手动重新加载页面可以正常工作,但我需要它自动刷新

我使用 monogoose 作为数据库和 rest api

注意:没有错误

【问题讨论】:

  • 天哪,格式化...
  • 别怪他。他对 SO 来说似乎很陌生。@n00dl3
  • 哎呀,@n00dl3 ...我是新的
  • @RahulRaveendran 你能分享一下 book.component.html 吗?
  • @n00dl3 谢谢老兄...:)

标签: angular observable


【解决方案1】:

首先,不要拼接成从左到右的循环,可以cause issues

removeBook(id: number) {
        var books = this.books;
        this.bookService.removeBook(id).subscribe(data => {
        if (data.n == 1) {
          let index = books.findIndex(book=>book.id===id)
          books.splice(i, 1);
        }
        });
    }

当您修改而不重新评估数组时,ngFor 不会收到通知,因为您没有指定 trackBy

<div *ngFor="let book of books; trackBy:trackById">

在你的 ts 文件中:

trackById(book:Book,index:number){
    return book.id;
}

否则,您可以只重新分配而不是修改组件中的数组:

this.bookService.removeBook(id).subscribe(data => {
            if (data.n == 1)
                this.books = this.books.filter(book=>book.id!==id);
        });

【讨论】:

    【解决方案2】:

    您可以按如下方式更改 book.component.ts 中的代码:

    export class BookComponent {
        books: Book[];
    
        constructor(private bookService: BookService) {}
    
        ngOnInit(){
            this.GetBooks();
        }
    
        GetBooks(){
            this.bookService.getBooks()
                .subscribe(books => {
                    this.books = books;
            });
        }
    
        removeBook(id: number) {
            var books = this.books;
            this.bookService.removeBook(id).subscribe(data => {
                this.GetBooks();
            });
        }
    }
    

    这里,方法GetBooks() 会在您从 api 获得响应时调用,并且您的页面将自动重新加载。

    【讨论】:

    • 很遗憾,这不是一个好的解决方案,因为很可能会进行两次服务器调用,除非 bookService 中有缓存机制。
    • 缓存无济于事,因为他只是向服务器发出了 DELETE 请求...
    • 如果您不想进行两次服务器调用,请在响应中重新加载页面。
    • "如果您不想进行两次服务器调用,请在响应中重新加载页面。"告诉我用什么魔法,它可以在重新加载页面时跳过服务器调用,我很好奇......
    • 在页面加载时调用GetBooks() 的方法,因此服务器调用肯定会完成。抱歉该评论。 @n00dl3
    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2020-01-22
    • 2018-01-18
    相关资源
    最近更新 更多