-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhow-add-todo-list-component-to-angular-from-wp
103 lines (68 loc) · 1.79 KB
/
how-add-todo-list-component-to-angular-from-wp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
cd src/app
mkdir todos
ng g component /todos/todo-list
ng g service /todos/todos
Add to app-routing.module.ts:
import { TodoListComponent } from './todos/todo-list/todo-list.component';
add to the routes inside app-routing.module.ts:
{
path: 'todos',
component: TodoListComponent,
pathMatch: 'full'
}
Run:
touch todos/todo.ts
inside todo.ts:
export class Todo {
}
Run:
ng g service /todos/todos
open todos.service.ts and make it look like this:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Todo } from './todo';
@Injectable()
export class TodosService {
private todosUrl = "localhost/wp-json/wp/v2/";
constructor(private http: Http) { }
getTodos(): Observable<Todo[]> {
return this.http
.get(this.todosUrl + 'todos')
.map((res: Response) => res.json());
}
}
Add to todo-list.ts:
import { Todo } from '../todo';
import { TodosService } from '../todos.service';
providers: [TodosService]
and to the export class:
todos: Todo[];
constructor( private todosService: TodosService ) { }
getTodos(){
this.todosService
.getTodos()
.subscribe(res => {
this.todos = res;
});
}
ngOnInit() {
this.getTodos();
}
// Authentication
todos.service.ts:
Add below the contructor.
createAuthorizationHeader(headers: Headers) {
headers.append('Authorization', 'Basic ' +
btoa('localhost:localhost'));
}
Then modify the getTodos to look like this:
getTodos(): Observable<Todo[]> {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get(this.todosUrl + 'todos', {
headers: headers
})
.map((res: Response) => res.json());
}