[英]Angular share data between service and two components
我需要從http獲取Post[]
,然后在post-list
組件上顯示它。 我可以刪除post-list
模板上post-list
某些項目,並通過導航到使用post-edit
組件的另一條路線來編輯某些項目。 如何在它們之間共享相同的Post[]
數組,以便更改將立即顯示在應用程序中? 我假設我需要在服務中存儲Post[]
? 從組件編輯/更新它的正確方法是什么? 這里我試圖通過服務內部的tap()
運算符將Post[]
數組保存在服務內部
getAllPosts(): Observable<Post[]> {
return this.http.get<Post[]>("https://jsonplaceholder.typicode.com/posts");
}
getAllUsersPosts(userId: number): Observable<Post[]> {
return this.getAllPosts().pipe(
map((posts: Post[]) => posts.filter((p: Post) => p.userId === userId)),
tap(posts => {
//storing to service
this.userPosts = posts;
})
);
}
刪除方法執行后共享更新的Post[]
我試圖將存儲的數組發送回訂閱服務器,但這無濟於事
deletePost(id: number): Observable<any> {
return this.http.delete(`https://jsonplaceholder.typicode.com/posts/${id}`).pipe(
mapTo(res => {
const index = this.userPosts.findIndex(p => p.id == id);
// console.log(index);
this.userPosts.splice(index, 1);
return this.userPosts;
})
)
}
實現此目的的正確方法是什么?
在服務中創建一個行為主題單例變量,並將其設置為可觀察的。 然后通過導入服務從任何組件訂閱該可觀察對象,創建一個實例並訂閱該可觀察對象。
private publisherVariable= new BehaviorSubject<string>('empty')
castVariable = this.publisherVariable.asObservable()
this.publisherVariable.next(DATA_YOU_WANT_TO_SEND)
userPosts的持久性將取決於注入的服務范圍。
嘗試為服務提供模塊作用域或根作用域
@module({
providers:[PostService]
})
export class PostModule{}
要么
@Injectable({
provideIn:'root'
})
export class PostService{}
避免在模塊和組件中都將postservice作為提供者。
@Componenent({
providers:[PostService]
})
export class PostComponent{}
創建一個模型並將其創建為一個singleton
,在您的服務中使用該singleton
singleton
,以便傳遞和更新相同的引用。
export class PostsModel {
private static instance: PostsModel;
public prop1: type = '';
public prop2: type ='';
static getInstance() {
if (!PostsModel.instance) {
PostsModel.instance = new PostsModel();
}
return PostsModel.instance;
}
static destroyInstance() {
delete PostsModel.instance;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.