正如標題所說,我正在嘗試從遵循單例模式的另一個類(評論)訪問在一個類(帖子)中宣告的方法。Post 類是一個服務類,它具有一些進行 API 呼叫的方法。所以我需要從 Comments 類中訪問它們,以便進行 API 呼叫。
這是 Post 類的簡化版本現在的樣子:
@Injectable({
providedIn: 'root'
})
class PostService extends AnotherService {
constructor( auth: AuthService, http: HttpClient ) {
super('string', auth, http);
}
getPost( id: string ) {
return this.http.get(`posts/${id}`);
}
}
這是 Comments 類的樣子:
class Comments {
private postService: PostService;
private static instance;
private constructor() {}
static createInstance() {
if ( !Comments.instance ) {
Comments.instance = new Comments();
}
return Comments.instance;
}
getComments( id ) {
// these does not even run
this.postService.getPost( id )
.then( post => {
console.log( post );
})
.catch( error => {
console.log( error );
});
}
}
我該如何訪問它?
=========更新=======
在另一個名為 ClassC 的類中創建 Comment 類的實體。
const instance - Comments.createInstance();
instance.getComments( id );
uj5u.com熱心網友回復:
使用新服務來保存您的評論物件資料假設我們有一個名為 SharedDataService 的服務。
private _comments: Array<any> =[];// or array<IComment> (a defined interface from your part)
class SharedDataService(){}
get comments():Array<any>{
return this._comments}
set comments(value:Array<any>){
this._comments = value;
}
}
您應該在您的評論建構式上初始化 PostService
private constructor(private postService: PostService,private sharedDataService :SharedDataService) {
}
getComments() {
// these does not even run
this.postService.getPost( '1' )
.then( post => {
this.sharedDataService.comments = post // if You get an array of comments here
console.log( post );
console.log(this.comments)// getter function its new value has been set
})
.catch( error => {
console.log( error );
});
get comments(){
this.sharedDataService.comments
}
}
uj5u.com熱心網友回復:
如果您想并行發送兩個 http 請求然后獲取它們的值您應該使用 combineLatest rxjs 運算子。您的郵政服務將是這樣的:
getPost(id: string) {
$postDataHttpRequest = this.http.get(`posts/${id}`);
$commentsDataHttpRequest = this.http.get(`posts/${id}/comments`);
return combineLatest($postDataHttpRequest, $commentsDataHttpRequest)
}
///
這是 Comments 類的樣子:
private constructor(private postService: PostService) {
}
getComments() {
this.postService.getPost( '1' )
.subscribe( (posts,comments) => {
console.log(posts);
console.log(comments);
},(error)=>{console.log(error)})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477970.html
標籤:javascript 有角度的
