angular6 页面传值_Angular6同步加载路线数据

Okay, I recently implemented SSR into my Angular6 application, with the intention of rendering dynamic HTML in a crawlable manner. All seems to be working fine, but my issue is rendering data from an API endpoint.

As soon as a user arrives on my site, a list of top posts that have been retrieved from a Node server will be displayed. In order to retrieve the data before page load, I implemented a resolver for my posts service. The resolver will resolve an Observable, which will then be accessed by my component.

resolver.service.ts :

import { Injectable } from '@angular/core';

import { Resolve } from '@angular/router';

import { PostService } from '../services/post.service';

import { of } from 'rxjs';

@Injectable()

export class ResolverService implements Resolve {

constructor(private postService: PostService) { }

resolve (){

return of(this.postService.getPosts());

}

}

This Observable will be correctly resolved and can be accessed in my component like so,

content.component.ts :

...

posts: any;

constructor(private route:ActivatedRoute){}

ngOnInit() {

this.route.snapshot.data['posts'].subscribe(

data =>{

this.posts = JSON.parse(JSON.stringify(data));

}

);

}

...

Then the posts variable will be rendered in the html. The problem is, when using a subscription, my data is not rendered in the source because subscriptions work asynchronously. I need the data to be extracted before page load.

If anyone can point me in the correct direction, it would be much appreciated. Thanks.

解决方案

Found the solution. I was previously using the HttpClient module to handle api calls, it turns out that I needed to use the Http module with the following approach I discovered thanks to @IftekharDani 's example.

resolver.service.ts:

import { Http } from '@angular/http';

...

getPosts(): Observable {

return this.http.get("/api/posts/all", { })

.pipe(

map(

res => {

return res.json();

},

err => {

return err;

}

)

);

}

resolve (route: ActivatedRouteSnapshot, state: RouterStateSnapshot){

return this.getPosts();

}

content.component.ts:

...

ngOnInit() {

this.posts = this.route.snapshot.data['posts'];

}

...

app-routing.module.ts

import { ResolverService } from './services/resolver.service';

const routes: Routes = [

...

{ path: '**', component: ContentComponent, resolve: { posts: ResolverService}}

];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值