本教程演示了使用wp-api-angular
庫將Angular 2應用程序與WordPress REST API連接的。 該圖書館支持主要的WP資源(用戶,帖子,評論,媒體,分類法)。我們將構建展示其易用性的功能:JWT身份驗證,用戶和發布列表,以及Post Crud(創建,讀取,更新,刪除)操作。 完整的源代碼在GitHub上。 雖然本教程使用Angular 5,但這些概念適用於Angular 2。
密鑰概念:
wp-api-angular
WordPress設置:啟用永久鏈接並安裝JWT身份驗證插件以進行安全API訪問。 本教程使用一個自託管的WordPress實例。 啟用永久鏈接(有關說明,請參見WordPress codex;有關NGINX,添加)。 安裝JWT身份驗證插件以供安全API訪問。
>try_files $uri $uri/ /index.php?$args;
Angular應用程序設置:nginx.conf
創建一個新的Angular應用程序:
ng new wp-api
中導入必要的模塊:cd wp-api && npm install wp-api-angular --save
src/app/app.module.ts
(包括<code class="language-typescript">import { Http } from '@angular/http'; import { HttpClientModule, HttpClient } from '@angular/common/http'; import { WpApiModule, WpApiLoader, WpApiStaticLoader } from 'wp-api-angular'; @NgModule({ // ... imports: [ BrowserModule, FormsModule, HttpClientModule, WpApiModule.forRoot({ provide: WpApiLoader, useFactory: WpApiLoaderFactory, deps: [Http] }) ], // ... }) export function WpApiLoaderFactory(http: Http) { return new WpApiStaticLoader(http, 'http://YOUR_DOMAIN_HERE/wp-json/wp/v2/', ''); }</code>)。
YOUR_DOMAIN_HERE
> authentication(JWT):app.component.ts
NgForm
HttpClientModule
Headers變量
創建一個component()。
>token
對象和app.component.ts
方法:authentication
ng generate component authentication
authentication.component.ts
user
auth()
列表用戶:<code class="language-typescript">auth() { this.http.post('http://YOUR_DOMAIN/wp-json/jwt-auth/v1/token', { username: this.user.login, password: this.user.password }).subscribe(data => { if (data['token']) { this.token = data['token']; this.tokenChange.emit(this.token); } }); }</code>創建
authentication.component.html
並使用來獲取用戶。 >
user-list
ng generate component user-list
>post-new
組件。 在JWT授權標題中使用WpApiPosts.create()
> post-list
組件。使用WpApiPosts.getList()
來獲取帖子。 post-list
> WpApiPosts.delete()
post-edit
> WpApiPosts.update()
結論:
以上是將角和WordPress API與wp-api-angular連接的詳細內容。更多資訊請關注PHP中文網其他相關文章!