首页 文章

正在调用Angular 2 http服务,但请求不会出去

提问于
浏览
0

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

例如,假设我有这些 endpoints :

/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
        ...
    });

为了实现这一点,我尝试使用工厂_177110_一个书籍模型的实例 . 然后我传入对工厂注入的Http注入依赖项的引用 .

这就是我所拥有的:

BooksService

@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 .

(为简洁起见,删除了导入语句)

1 回答

  • 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<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调用 .

相关问题