且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular2路由-URL不变,页面不加载

更新时间:2022-05-07 23:06:49

我最初遇到的问题取得了一些进展.因为我正在学习angular2及其所有功能,所以我最初编写的代码是当用户从主页转到带有url book/1的书页时使用subscribe的代码.

I made some progress with my initial problem. Because I'm learning angular2 and everything that I can do with it, I originally wrote the code to use subscribe when the user goes from the home page to the book page with url book/1 for example.

但是由于我收到模板错误,现在我已经更改了使用订阅的方式.

However I've now changed the way I'm using subscribe because I was getting a template error.

我以前在ngOnInit上使用过它:

I was using this before on ngOnInit:

ngOnInit() {
    this.libraryService.getBooks().subscribe(response => {
        this.books = response;
    });
}

但是现在我将其更改为:

But now I've changed it to this:

ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            const id = params["id"];
            this.book = this.libraryService.getBook(id);
        });
    }

使用订阅现在感觉有点多余,因为因为这只是一个简单的api调用,所以我不必在角度代码中观察任何内容.

Using subscribe now feels a bit redundant because because it's just a simple api call, I don't have to observe anything in my angular code.

我现在将在此处保留此答案,但是如果有人有更好的答案并附有解释,我会将其答案标记为正确.

I'll leave this answer here for now but if anyone has a better answer with an explanation I'll mark their answer as correct.