【问题标题】:Angular2 get page data from Wordpress WP APIAngular2 从 Wordpress WP API 获取页面数据
【发布时间】:2017-06-26 00:23:27
【问题描述】:

我正在使用 Wordpress WP API 将数据解析到我的 Angular2 应用程序中。

我需要获取数据来填充我的页面,并且我需要根据 ActivatedRoute 获取页面 SLUG。但是,我不确定如何实现这一点。在“项目”页面中,我需要有页面数据。

这是我的页面数据的示例 Json:

[{
  "id":16,
  "date":"2015-06-24T11:44:03",
  "slug":"projects",
  "type":"page",
  "title":{"rendered":"Projects"}
}]

首先,我创建了一个页面服务:

@Injectable()
export class PageService {

constructor(private http: Http) {}

getPage(slug): Observable<Page>  {

    return this.http
        .get(`${PROJECT_API}pages?slug=${slug}`)
        .map((res: Response) => res.json());
}

}

然后,在我的 app.component 中,我尝试获取激活的路由参数,将 SLUG 解析为我的 Service 中的 getPage 函数:

export class AppComponent implements OnInit {

   page: Page[]; // Interface of Page

   constructor(
       private router: Router,
       private activatedRoute: ActivatedRoute,
       private pageService: PageService
   ) {}

   ngOnInit() {
        this.activatedRoute.params
          .switchMap((data: Page) =>   this.pageService.getPage(data.slug))
          .subscribe((data: Page) => {
            console.log(data[0])
            this.page = data[0]
          });

   }

}

在我的控制台中,我得到“未定义”。

我希望每个页面从 ActivatedRoute 动态获取页面 SLUG 并获取数据以填充每个页面。

对于每个页面(组件模板),我可以简单地解析:

<h1>{{ page?.title.rendered }}</h1>

我在这里错过了什么?

【问题讨论】:

    标签: javascript json wordpress angular


    【解决方案1】:

    我正在开发一个插件,Xo for Angular,这听起来像是解决这种情况的完美解决方案。

    https://wordpress.org/plugins/xo-for-angular/

    主要概念:

    • 您的 Angular 应用程序已加载并作为主题存在于 WordPress 中。
    • 可为页面和帖子选择的 Angular 模板(模块)。
    • 在 WordPress 中创建的页面、帖子和其他内容的动态路由。

    使用 Xo API 可以轻松获取 WordPress 中任何页面或帖子的数据。例如:https://angularxo.io/xo-api/posts/get?url=/

    这会检索完整的帖子对象,并添加元和 ACF 字段(如果已配置)。

    Xo 还动态生成所有路由,这让您可以通过 WordPress 正常定义页面结构。无需通过 slug 检索页面或帖子,因为 WordPress 和 Angular 因为 Xo 使它们保持完全同步。

    动态路由示例:https://angularxo.io/xo-api/routes/get

    还有一个节点模块angular-xo,它提供了一个内置解析器来检索每个页面视图的这些数据,并使这些数据在您的模板中可用。

    有关此功能的更多信息:https://angularxo.io/guides/routing

    使用 Xo 的示例主题:https://github.com/WarriorRocker/angular-xo-material

    更多文档(正在进行中):https://angularxo.io/

    【讨论】:

      猜你喜欢
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2017-08-15
      相关资源
      最近更新 更多