我是angular 4的新手,我创建了一个api来从我的数据库中获取数据并显示或更新它或创建一个新数据。我知道如何显示数据,但我不知道如何更新或创建数据。我创建了api.services.ts:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
import { Article } from './../models/article';
import { Category } from './../models/category';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiService {
constructor(private http: Http) { }
getAllArticle(pagenumber: number): Observable<any> {
return this.http.get('http://localhost/api/articles?page=' + pagenumber)
.map(res => res.json());
}
getArticle(slug: string): Observable<Article>{
return this.http.get('http://localhost/api/article/' + slug)
.map(res => res.json());
}
getAllCategory(): Observable<Category[]>{
return this.http.get('http://localhost/api/categories')
.map(res => res.json());
}
getCategoryArticle(slug : string) : Observable<any>{
return this.http.get('http://localhost/api/article/category/' + slug)
.map(res => res.json());
}
}
&#13;
我创建了single-article.component.ts:
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../services/api.services';
import { Article } from '../models/article';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-single-article',
templateUrl: '/../../templates/single-article.component.html',
providers: [ApiService]
})
export class SingleArticleComponent implements OnInit {
article: Article;
constructor(private route: ActivatedRoute, private api: ApiService) { }
ngOnInit(): void {
this.route.params
.map((params: Params) => params['slug'])
.switchMap(slug => this.api.getArticle(slug))
.subscribe(article => this.article = article);
}
}
&#13;
显示数据,但我不知道如何创建update-article.component.ts。我怎么能这样做?
答案 0 :(得分:0)
只需使用this.http.get('http://localhost/api/article/category/' + slug)
更改this.http.put('http://localhost/api/article/category/' + slug, data)
即可。调用this.http时使用PUT或POST方法,并将对象数据作为第二个参数传递。