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 { }
のApp成分
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);
}
);
}
}
IAM呼び出しが作成しgetpa app.component.htmlのclickイベントからrticular。コアサービスは、私がrequest.pleaseにこれを解決するためにhttpコールをしていません。私はrxjsがこの問題の原因だと思う。 私はここに複製しました - >https://stackblitz.com/edit/angular-rcxgxv。
実際には、1つの残りの呼び出しでフェッチエンドポイントを作成します。つまり、coreserviceメソッドを実行する前に、(通常はコンストラクタ内で)エンドポイントを取得するために残りの呼び出しを行います。 Common.Socket.next( 'https://reqres.in'); - >このエンドポイント(https://reqres.in)は動的です。 –
この回答によると、エンドポイントは静的です。私はそれを動的にしたい。 –
エンドポイントのデータを取得して格納するサービスを使用することができます。エンドポイントのデータと機能を持つオブジェクトを持つことができます。この関数を呼び出すと、オブジェクトはデータで満たされます。そして、あなたは単にexampleService.endpoints.allUsersを実行できます。 exampleServiceコンストラクターでエンドポイントを取得する関数を呼び出すことができ、すべてのサービスでエンドポイントデータにアクセスできます。 – MateuszWkDev