【问题标题】:Angular 2+ http service is being called, but request is not going outAngular 2+ http 服务被调用,但请求没有发出
【发布时间】:2017-05-01 02:43:47
【问题描述】:

我希望能够实例化一个模型类,同时也让它能够访问服务。

例如,假设我有这些端点:

/book/:id
/book/:id/author

我想要一个BooksService 服务来获取Book 实例的列表。我希望使用new 实例化书籍实例,通过构造函数给出定义 JSON,同时仍然能够使用 Angular 依赖项。

我想做的例子:

BooksService.getBook(1)       // makes call to /book/1
    .subscribe((book) => {
        book.getAuthor()  // makes call to /book/1/author
        ...
    });

为了做到这一点,我尝试使用一个工厂来new 一个书本模型的实例。然后我传入对工厂注入的 Http 注入依赖项的引用。

这是我所拥有的:

图书服务

@Injectable()
export class BookService {
    constructor(
        private http: Http,
        private bookModelFactory: BookModelFactory
    ) {}

    getBook(): Observable<BookModel> {
        return this.http.get('http://localhost:3000/book/1')
            .map((res) => {
                return this.bookModelFactory.make(res.json().data);
            });
    }
}

BookModel、BookModelFactory

@Injectable()
export class BookModelFactory {
    constructor (private http: Http) {}

    make(def: object): BookModel {
        var book = new BookModel(def);
        book.http = this.http;
        return book;
    }
}

export class BookModel {
    def: any;
    http: Http;

    constructor (def: object) {
        this.def = def;
    }

    getAuthor() {
        console.log('http', this.http);
        this.http.get('http://localhost:3000/book/1/author');
    }
}

当我尝试使用此代码时,我在 book.getAuthor() 中看到了 http 对象的控制台日志。它存在,我可以在上面看到get 方法。但它从不发出 API 请求。网络选项卡中没有任何关于调用/book/1/author 的内容。没有错误。简而言之,什么都没有发生。

为什么在getAuthors() 中调用this.http.get('...') 时没有发出请求?

提前致谢。

使用 Angular 4。

(为简洁起见,移除了 Imports 语句)

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    2) 如果这是一个好策略...为什么在 getAuthors() 中调用 this.http.get('...') 时没有发出请求?

    因为没有人订阅此调用的结果:

    this.http.get('http://localhost:3000/book/1/author').subscribe(res => {
        // do something with the results here
    });
    

    如果你不订阅 HTTP 调用的结果,那么这个调用将永远不会进行。

    或者您可能希望您的getAuthor 方法返回一个Observable&lt;Author&gt;,以便该方法的调用者可以订阅结果:

    getAuthor(): Observable<Author> {
        return this.http.get('http://localhost:3000/book/1/author').map(res => {
            return res.json().data;
        });
    }
    

    以便您以后可以订阅:

    BooksService.getBook(1)       // makes call to /book/1
        .subscribe(book => {
            book.getAuthor() // makes call to /book/1/author
                .subscribe(author => {
                    // do something with the book author here
                });
            ...
        });
    

    所以请记住,如果您不订阅,则不会进行 AJAX 调用。

    【讨论】:

    • 啊,有趣,我只是想它会立即触发 GET 请求,然后注册 .map 和 .subscribe 以处理返回的任何内容。现在可以使用了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    相关资源
    最近更新 更多