1
CoreService :HTTP 요청이이 코드에서 발생하지 않습니까?
export class CoreService {
constructor(private _http: HttpClient) {
Common.Socket.next('https://reqres.in');
}
httpget(url): any {
return Common.Socket
.switchMap((x)=> this._http.get(x + url));
}
httppost(url, body): any {
return Common.Socket
.switchMap((x)=> this._http.post(x + url, body,
{headers: this.createAuthorizationHeader()}
));
}
private createAuthorizationHeader() {
const headers = new HttpHeaders({'Content-Type':'application/json'});
return headers;
}
}
구성 요소 서비스 :
export class AppServiceService {
constructor(private _coreService: CoreService) { }
getAll(path: string){
return this._coreService.httpget(path);
}
getParticular(url){
return this._coreService.httpget(url);
}
create(url, body) {
return this._coreService.httppost(url, body);
}
}
APP 모듈 :
@NgModule({
imports: [ BrowserModule, FormsModule, HttpClientModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: [CoreService]
})
export class AppModule { }
export class AppComponent implements OnInit {
name = 'Angular 5';
public allPosts: any;
constructor(private _appServiceService: AppServiceService) {
}
ngOnInit(): void {
this.getAllPosts();
}
private getAllPosts(): void {
this._appServiceService.getAll('/api/users?page=2').subscribe(
(res) => {
this.allPosts = res;
console.log(this.allPosts, 'allposts');
}
);
}
getParticular(): void {
this._appServiceService.getParticular('/api/users/2').subscribe(
(res) => {
this.allPosts = res;
console.log(this.allPosts, 'allposts');
}
);
}
createMessage() {
const url = '/api/users';
const body = { 'name': 'morpheus-1','job': 'leader'};
this._appServiceService.create(url, body).subscribe(
(x) => {
console.log(x);
}
);
}
}
이
스피 호출 만들 응용 프로그램 구성 요소 및 getpa app.component.html의 click 이벤트에서 rticular. 코어 서비스는 내가 요청할 때 HTTP 호출을하지 않습니다. 이것을 해결할 솔루션을 제공하십시오. 나는이 문제를 일으키는 rxjs라고 생각한다. 여기에 재현했습니다 ->https://stackblitz.com/edit/angular-rcxgxv.
실제로 하나의 나머지 호출은 끝점 호출을 만듭니다. 즉 coreservice 메서드를 실행하기 전에, 나는 (일반적으로 생성자에서) 끝점을 얻기 위해 나머지 호출을 할 것이다. Common.Socket.next ('https://reqres.in'); ->이 끝점 (https://reqres.in)은 동적입니다. –
이 답변에 따라 끝 점이 정적입니다. 나는 그것을 역동적으로 만들고 싶다. –
이므로 엔드 포인트의 데이터를 가져와 저장하는 서비스를 사용할 수 있습니다. 종점 데이터와 기능을 가진 객체를 가질 수 있습니다. 이 함수를 호출하면 끝점 객체가 데이터로 채워집니다. 그리고 exampleService.endpoints.allUsers 만 할 수 있습니다. exampleService 생성자에서 끝점을 가져 오는 함수를 호출 할 수 있으며 모든 서비스에 대해 끝점 데이터에 액세스 할 수 있습니다. – MateuszWkDev