我試圖創建一個服務來共享兩個組件之間的數據。我將該服務注入到根模塊中,以便通過在根模塊提供程序中執行DI來在整個應用程序中訪問該服務。我的代碼看起來大致如此。Angular 4 Singleton Services
服務
@Injectable(){
export class ForumService{
forum: any;
setForum(object){
this.forum = object;
}
getForum(){
return this.forum;
}
}
根模塊
.......
import { ForumService } from 'forumservice';
.......
@NgModule({
declarations: [.....],
imports: [.....],
providers: [....., ForumService],
bootstrap: [AppComponent]
})
export class AppModule{}
部件的一個
//A bunch of import statements
import { ForumService } from 'forumservice'; //Without this Angular throws a compilation error
@Component({
selector: 'app-general-discussion',
templateUrl: './general-discussion.component.html',
styleUrls: ['./general-discussion.component.css'],
providers: [GeneralDiscussionService] //Not injecting ForumService again
})
export class GeneralDiscussionComponent implements OnInit{
constructor(private forumService: ForumService){}
ngOnInit(){
helperFunction();
}
helperFunction(){
//Get data from backend and set it to the ForumService
this.forumService.forum = data;
console.log(this.forumService.forum); //prints the data, not undefined
}
}
組件兩個
//A bunch of import statements
import { ForumService } from 'forumservice'; //Without this Angular throws a compilation error
@Component({
selector: 'app-forum',
templateUrl: './forum.component.html',
styleUrls: ['./forum.component.css'],
providers: []
})
export class ForumComponent implements OnInit {
forumData: any;
constructor(private forumService: ForumService){}
ngOnInit(){
this.forumData = this.forumService.forum; // returns undefined
}
}
有一次,我從組件之間導航,組件兩個我期待「這是一個字符串」。但我得到undefined
。是否因爲組件中的導入語句?如果我刪除,我看到一個編譯錯誤說沒有找到ForumService
。
我很確定這是一個計時問題,在設置之前讀取值。嘗試在構造函數中設置而不是'ngOnInit'。我的建議是使用'BehaviorSubject'來解決這種問題,而不是一個公正的領域。 –