javascript - 角度获取 api
问题描述
我的 api 是http://dradiobeats.x10host.com/public/api/areas
我的 app.component.ts:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { Post } from './post.model';
import { PostsService } from './posts.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
loadedPosts: Post[] = [];
isFetching = false;
error = null;
private errorSub: Subscription;
constructor(private http: HttpClient, private postsService: PostsService) {}
ngOnInit() {
this.errorSub = this.postsService.error.subscribe(errorMessage => {
this.error = errorMessage;
});
this.isFetching = true;
this.postsService.fetchPosts().subscribe(
posts => {
this.isFetching = false;
this.loadedPosts = posts;
},
error => {
this.isFetching = false;
this.error = error.message;
}
);
}
onCreatePost(postData: Post) {
// Send Http request
this.postsService.createAndStorePost( postData.id, postData.name, postData.domain, postData.description , postData.picture);
}
onFetchPosts() {
// Send Http request
this.isFetching = true;
this.postsService.fetchPosts().subscribe(
posts => {
this.isFetching = false;
this.loadedPosts = posts;
},
error => {
this.isFetching = false;
this.error = error.message;
console.log(error);
}
);
}
onClearPosts() {
// Send Http request
this.postsService.deletePosts().subscribe(() => {
this.loadedPosts = [];
});
}
onHandleError() {
this.error = null;
}
ngOnDestroy() {
this.errorSub.unsubscribe();
}
}
我的posts.service.ts
import { Injectable } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpEventType
} from '@angular/common/http';
import { map, catchError, tap } from 'rxjs/operators';
import { Subject, throwError } from 'rxjs';
import { Post } from './post.model';
@Injectable({ providedIn: 'root' })
export class PostsService {
error = new Subject<string>();
constructor(private http: HttpClient) {}
createAndStorePost( id: string,
name: string,
description: string,
domain: string,
picture: any ) {
const postData: Post = { id , domain , name, description, picture };
this.http
.post<{ name: string , description: string , domain: string , picture: string }>(
'http://dradiobeats.x10host.com/api/areas',
postData,
{
observe: 'response'
}
)
.subscribe(
responseData => {
console.log(responseData);
},
error => {
this.error.next(error.message);
}
);
}
fetchPosts() {
let searchParams = new HttpParams();
searchParams = searchParams.append('print', 'pretty');
searchParams = searchParams.append('custom', 'key');
return this.http
.get<{ [key: string]: Post}>(
'http://dradiobeats.x10host.com/api/areas',
{
headers: new HttpHeaders({ 'Custom-Header': 'Hello' }),
params: searchParams,
responseType: 'json'
}
)
.pipe(
map(responseData => {
const postsArray: Post[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postsArray.push({ ...responseData[key], id: key });
}
}
return postsArray;
}),
catchError(errorRes => {
// Send to analytics server
return throwError(errorRes);
})
);
}
deletePosts() {
return this.http
.delete('http://dradiobeats.x10host.com/api/areas', {
observe: 'events',
responseType: 'text'
})
.pipe(
tap(event => {
console.log(event);
if (event.type === HttpEventType.Sent) {
// ...
}
if (event.type === HttpEventType.Response) {
console.log(event.body);
}
})
);
}
}
我的posts.model.ts
export interface Post {
id: string;
name: string;
domain: string;
description: string;
picture: any;
}
我的 logging-interceptor.service.ts
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEventType
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
export class LoggingInterceptorService implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
console.log('Outgoing request');
console.log(req.url);
console.log(req.headers);
return next.handle(req).pipe(
tap(event => {
if (event.type === HttpEventType.Response) {
console.log('Incoming response');
console.log(event.body);
}
})
);
}
}
我的 auth-interceptor.service.ts
import {
HttpInterceptor,
HttpRequest,
HttpHandler
} from '@angular/common/http';
export class AuthInterceptorService implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedRequest = req.clone({
headers: req.headers.append('Auth', 'xyz')
});
return next.handle(modifiedRequest);
}
}
我的应用程序-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我的 app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AuthInterceptorService } from './auth-interceptor.service';
import { LoggingInterceptorService } from './logging-interceptor.service';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: LoggingInterceptorService,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptorService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
我的 app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'ng-complete-guide-update'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('ng-complete-guide-update');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-complete-guide-update!');
});
});
我的 app.component.html
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'ng-complete-guide-update'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('ng-complete-guide-update');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-complete-guide-update!');
});
});
我的 app.component.css
.container {
margin-top: 30px;
}
.row {
margin: 20px 0;
}
我只获取数据而不是元素 [id ,name,description,domain,picture] 为什么?
解决方案
推荐阅读
- android - 我想使用 jsoup 在我的 android 应用上获取新闻
- python - 如何控制 Airflow 安装的并行性或并发性?
- typescript - 使用枚举定义接口上的键列表
- python - 下划线分隔数字的数字是什么类型?
- android - 数据库未将数据从一项活动更新到另一项活动
- docker - docker compose 不会构建
- excel - 将单元格的值引用到另一个工作表中的值时类型不匹配
- php - PHP,变量不会附加到超链接
- forms - 有没有办法通过 NOT REQUIRED v-text-field 规则的验证?
- javascript - 分数没有更新。你能告诉我代码有什么问题吗?