Angular4 +主题不断循环回呼功能

时间:2018-08-18 15:31:18

标签: angular service rxjs observable behaviorsubject

我正在使用MEAN堆栈创建博客,但我的BehaviorSubject遇到问题。我有一个登录页面,一个导航栏和一个包含一些帖子的仪表板。登录时,我使用router-link自动进入仪表板。我在仪表板上的每个帖子都有一个按钮,该按钮使用router-link转到该帖子。但是,当我单击该按钮时,页面仪表板消失了,但是没有去博客文章,而是重新出现了仪表板,而且我们再也没有到达博客文章的页面。

对于每个组件,我都会检查用户是否登录,因为如果用户登录,则会显示一个略有不同的视图。我将用户是否登录存储在本地存储中,并且有一个检查本地存储的服务。我在ngOnInit方法中对该服务进行了调用。

我到处都放置console.log语句,我发现当我单击博客帖子时,它会检查用户是否通过blogPost组件ngOnInit登录(应该如此)。但是,它还会检查用户是否从仪表板组件登录。然后,它返回到blogPost组件,并检查用户是否再次登录。我认为此循环导致了我的问题。

由于某种原因,当我刷新页面然后单击博客文章时,它可以工作,但是否则,在立即登录后,它就没有作用。

import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject'; 

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {

  loginBoolean: boolean;
  public listener = new BehaviorSubject(false);
  constructor(
  ) { 
    this.loginBoolean = JSON.parse(localStorage.getItem('isLoggedIn'))
  }


  loginTrue() {
    console.log("Setting login to true");
    localStorage.setItem('isLoggedIn', 'true');
    this.loginBoolean = JSON.parse(localStorage.getItem('isLoggedIn'));
    this.listener.next(this.loginBoolean);
    return this.listener.asObservable();
  }

  loginFalse() {
    console.log("setting login to false");
    localStorage.setItem('isLoggedIn', 'false');
    this.loginBoolean = JSON.parse(localStorage.getItem('isLoggedIn'));
    this.listener.next(this.loginBoolean);
    return this.listener.asObservable()
  }

  isLoggedIn(location?: string) {
    console.log("Checking we're logged in from " + location);
    console.log(this.loginBoolean);
    this.loginBoolean = JSON.parse(localStorage.getItem('isLoggedIn'));
    this.listener.next(this.loginBoolean);

    return this.listener.asObservable();
  }
 }

这是仪表板组件的打字稿文件

import { Component, OnInit } from '@angular/core';

import { NewPostService } from '../../services/new-post.service';
import { LocalStorageService } from '../../services/local-storage.service';

import { BlogPost } from '../../models/blog-post.model'

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  listOfPosts: BlogPost[];
  isLoggedIn: boolean;
  constructor(
    private newPostService: NewPostService,
    private localStorageService: LocalStorageService
  ) { }

  ngOnInit() {
    this.localStorageService.isLoggedIn("dashboard-component").subscribe((res) => {
      this.isLoggedIn = res;
    })
    this.listPosts()
  }

  listPosts() {
    this.newPostService.getBlogPosts().subscribe((posts) => {
      this.listOfPosts = posts as BlogPost[];
    });
  }
}

这是仪表板组件的html文件

<button *ngIf="isLoggedIn" routerLink="createPost">Create a Post</button>
<div *ngFor="let post of listOfPosts">
  <li>{{post.author}}</li>
  <li>{{post.date}}</li>
  <li>{{post.text}}</li>
  <button routerLink="blogPost/{{post._id}}">Go to Page</button>
</div> 

这是blogPost组件的打字稿文件

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

import { NewPostService } from '../../services/new-post.service';
import { LocalStorageService } from '../../services/local-storage.service';

import { BlogPost } from '../../models/blog-post.model';

@Component({
  selector: 'app-blog-post',
  templateUrl: './blog-post.component.html',
  styleUrls: ['./blog-post.component.css']
})
export class BlogPostComponent implements OnInit {
  selectedPost: BlogPost;
  isDataAvailable: boolean = false;
  isLoggedIn: boolean;

  constructor(
    private route: ActivatedRoute,
    private newPostService: NewPostService,
    private location: Location,
    private localStorageService: LocalStorageService,
    private router: Router
  ) {
  }

  ngOnInit() {
    console.log("We about to grab a single blog post");
    this.localStorageService.isLoggedIn("blog-post-component").subscribe((res) => {
      console.log("We're int the callback function, getting blog post");
      console.log("The response is " + res);
      this.isLoggedIn = res;
    });
    console.log("We're outside of the call back function, getting the ID")
    this.getId();
  }

  getId() {
    let objectId = this.route.snapshot.paramMap.get('id');
    console.log("We're outside of the callback function getting post: " + objectId);
    this.newPostService.getBlogPost(objectId).subscribe((post) => {
      console.log("We're inside of the callback function getting post: " + objectId);
      this.selectedPost = post as BlogPost;
      this.isDataAvailable = true;
    });
  }

  onDelete(post_id: string) {
    if(confirm("Are you sure you want to delete this post?")) {
      this.newPostService.deletePost(post_id).subscribe((res) => {
        this.router.navigateByUrl('');
      });
    }
  }
}

0 个答案:

没有答案