我希望能够实例化模型类,同时也为其提供服务访问权限。
例如,假设我有这些端点:
/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
...
});
为了实现这一目标,我尝试使用工厂来新建
书籍模型的实例。然后,我传入对工厂注入(inject)的 Http 注入(inject)依赖项的引用。
这是我所拥有的:
图书服务
@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。
(为简洁起见,删除了导入语句)
最佳答案
2) If this is a good strategy... why isn't the request being made when this.http.get('...') is being called in getAuthors()?
因为没有人订阅此通话的结果:
this.http.get('http://localhost:3000/book/1/author').subscribe(res => {
// do something with the results here
});
在 Angular 中,如果您不订阅 HTTP 调用的结果,则永远不会进行此调用。
或者也许您想要您的 getAuthor
方法返回 Observable<Author>
这样该方法的调用者就可以订阅结果:
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 调用。
关于javascript - Angular 2+ http 服务正在被调用,但请求没有发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43688663/