问题
I have this navbar, when I refresh the table, the data is fetched but when I move from links to links and go back to the link where the table is located. the data is not fetched or unknown. The problem occurs after I implemented the routers of the page. How can I fetch the data normally even I go back and forth with the links from the navbar. Im using firebase as my database
here is the app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
...
...
// All are imported correctly
import { SignInComponent } from './components/sign-in/sign-in.component';
const routes: Routes = [
{ path: '', redirectTo: '/sign-in', pathMatch: 'full' },
{ path: 'books', component: BooksComponent },
{ path: 'add-book', component: AddBookComponent },
{ path: 'sign-in', component: SignInComponent },
{ path: 'sign-up', component: SignUpComponent },
{ path: 'dashboard', component: DashboardComponent }
]
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
SERVICE (book.service)
constructor(public afs: AngularFirestore) {
this.booksCollection = afs.collection<Book>('books');
//this.books = this.afs.collection("books").valueChanges();
// get the data and the id use the map operator.
this.books = this.booksCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Book;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
}
getBooks(){
return this.books;
}
COMPONENT (book.component.html)
<ul class="list-group">
<li *ngFor="let book of books" class="list-group-item">
<div class="row">
<div class="col"><strong>{{book.title}}: </strong> {{book.description}}</div>
<div class="col-sm-auto">
<button (click)="editBook($event, book)" class="btn btn-link">Update</button>
</div>
<div class="col-sm-auto">
<button (click)="deleteBook($event, book)" class="btn btn-link">Delete</button>
</div>
</div>
</li>
</ul>
BOOK TYPE SCRIPT
books: Book[];
constructor(public bookService: BookService) { }
ngOnInit() {
this.bookService.getBooks().subscribe(books =>{
this.books = books;
});
}
NAVBAR
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<div *ngIf="user$ | async"><li class="nav-item"><a class="nav-link" routerLink="books">Books</a></li></div>
<div *ngIf="user$ | async"><li class="nav-item"><a class="nav-link" routerLink="add-book">Add Book</a></li></div>
<div *ngIf="user$ | async"><li class="nav-item"><a class="nav-link" routerLink="sign-in">Sign In</a></li></div> <!--Hide this link-->
<div *ngIf="user$ | async"><li class="nav-item"><a class="nav-link" routerLink="sign-up">Sign Up</a></li> <!--Hide this link--></div>
</ul>
</div>
来源:https://stackoverflow.com/questions/57645988/data-is-unknown-cannot-be-fetched-when-link-is-clicked-after-implementing-rou