Issue
I have a basic app structure where I call data (the iPhones in the database) from the AppComponent itself.
ngOnInit(): void {
this.iphoneservice.fetchIphones();
}
The fetchIphones method is in my iPhoneService file where I have 3 functions.
iPhoneList:iPhone[]=[]
fetchIphones(){
this.http
.get('https://angular-project-62585-default-rtdb.firebaseio.com/iphone.json')
.pipe(
map(responseData =>{
const postArray =[];
for(const key in responseData){
if(responseData.hasOwnProperty(key)){
postArray.push({...responseData[key],id:key});
}
}
return postArray
})
)
.subscribe(post =>{
this.generateIphoneList(post)
})
}
// Generating the IphoneList from the fetched Data
generateIphoneList(post){
this.iPhoneList=[];
for (let iphones of post){
let iphone = new iPhone()
for (let property in iphones){
iphone[property]=iphones[property];
}
this.iPhoneList.push(iphones);
}
}
// Returning the IphoneList to desired components
getiPhone(){
return this.iPhoneList;
}
The First two functions create the iPhoneList array and after that from my iPhoneFront-Component I retrive the data from the with the getiPhone function.
ngOnInit(): void {
this.iPhoneList=this.iphoneservice.getiPhone();
}
My Problem is that when I go to the page via the Navbar the data is fetched and visible, but if I go to the webpage manually via the URL the data is not fetched. My HTML for the navbar and the AppModule are below.
<li class="nav-item">
<a class="nav-link" routerLink="/iphone" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">iPhone</a>
</li>
const appRoutes : Routes =[
{path:'iphone',
children:[
{path:'',component:IphonefrontComponent},
{path:':id',component:IphonedetailComponent},
]
},
{path:'iphone-managing',
canActivate:[AuthenticationGuard],
children:[
{path:'',component:IphonebackComponent},
{path:'create',component:IphonecreateComponent},
{path:':id',component:IphoneeditComponent},
]},
{path:'cart',component:CartComponent},
{path:'authentication',component:AuthenticationComponent},
]
Thanks in Advance :)
Solution
After Henrik Bøgelund Lavstsen answer I declared Behavior Subject and changed my Service accordingly.
iPhoneList:iPhone[]=[];
iPhoneListSubject = new BehaviorSubject(this.iPhoneList);
generateIphoneList(post){
this.iPhoneList=[];
for (let iphones of post){
let iphone = new iPhone()
for (let property in iphones){
iphone[property]=iphones[property];
}
this.iPhoneList.push(iphones);
this.iPhoneListSubject.next(this.iPhoneList)
}
}
getiPhone(){
return this.iPhoneListSubject;
}
And after the getiPhone method is called I subsribed to the Behavior Subject.
iPhoneList:iPhone[]=[]
ngOnInit(): void {
this.iphoneservice.getiPhone().subscribe(
list=>{
this.iPhoneList=list
}
);
}
Answered By - Ekrem Üçüncü
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.