刷新页面后数据丢失

时间:2018-06-08 16:44:13

标签: angular django-rest-framework observable

我正在尝试使用Angular 5和DjangoRest Framework构建一个网站。 我在左侧有一个侧边栏,显示给定用户所属的关联列表。当我点击其中一个元素时,它会向我提供有关主要组件(myassoc.ts)上的关联的详细信息。当我点击它时,我用sidebar.component.html传递参数(关联的id),它显示了主要组件的预期输出。但是,当我刷新页面时,所有数据都会消失。我认为我有一个可观察的问题,但我真的不知道到底是什么。

是什么导致我这个错误,我该如何解决?非常感谢!

sidebar.component.html

    <li><a href="#exampledropdownDropdown" aria-expanded="false" data-toggle="collapse"> <i class="icon-windows"></i>Mes Assocs </a>
        <ul id="exampledropdownDropdown" class="collapse list-unstyled ">
          <li *ngFor="let i of assocs"><a [routerLink]="['mesassocs']" [queryParams]="{id: i.id}">{{ i.name }} {{i.id}}</a></li>
        </ul>
      </li>

sidebar.component.ts

import { Component, OnInit } from '@angular/core';
import { User } from '../../models/User';
import { Assoc } from '../../models/Assoc';
import { AssocService } from '../../services/assoc.service';
import { DataService } from '../../services/data.service';
import { Subscription } from 'rxjs';
import { GlobalService } from '../../services/global.service';
import { UserassosService } from '../../services/userassos.service';



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


  assocs: any = [];
  account: User = new User();
  userSub: Subscription;

  constructor(
    private dataService: DataService,
    private assocService: AssocService,
    private global: GlobalService,
    private userAssoc: UserassosService
  ) { }

  ngOnInit() {

    this.getAssocs();

    this.userSub = this.global.user.subscribe(
      me => {
        console.log('me', me);
        this.account = me;
      }
    );

    console.log(this.assocs);
  }

  getAssocs(): void {
    this.userAssoc.getUserassocs().subscribe(assocs => this.assocs = 
assocs);
  }

}

myassoc.component.ts

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

// Not sure if really needed to extract data from user.
import { User } from '../../models/User';
import { DataService } from '../../services/data.service';
import { AssocService } from '../../services/assoc.service';
import { GlobalService } from '../../services/global.service';
import { Subscription } from 'rxjs';


@Component({
  selector: 'app-myassoc',
  templateUrl: './myassoc.component.html',
  styleUrls: ['./myassoc.component.css',]
})

export class MyassocComponent implements OnInit {

  //Properties
  account: User = new User();
  userSub: Subscription;
  assoc: any;


  constructor(
    private dataService: DataService,
    private assocService: AssocService,
    private route: ActivatedRoute,
    private location: Location,
    private global: GlobalService,
    private router: Router
  ) {}

  ngOnInit() {
    this.userSub = this.global.user.subscribe(
      me => this.account = me
    );
    if (localStorage.getItem('token') && localStorage.getItem('account')) {
      this.global.me = JSON.parse(localStorage.getItem('account'));
      this.getAssocs();
    } else {
      this.router.navigate(['/home']);
    }
  }



  getAssocs() {
    this.route.queryParams.subscribe(
      (queryParams: Object) => {this.assoc = 
this.assocService.getAssocById(queryParams['id']);
      console.log(this.assoc);
    }
    );    
  }
}

assoc.service.ts

import { Injectable } from '@angular/core';
import { Assoc } from '../models/Assoc';
import { DataService } from './data.service';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';

import { UserassosService } from './userassos.service';
import { AssociationService } from './association.service';


@Injectable()
export class AssocService {
  assocs: any = [];
  userassocs;
  all_associations;
  my_assocs: any[];

  httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json; 
charset=utf-8' });
  baseUrl: string = environment.apiUrl;

  constructor(
    private dataService: DataService,
    private userAssoc: UserassosService,
    private associationService: AssociationService,
    private http: HttpClient
  ) {
    this.getAssocs();  
  }

getAssocById(id: number) {
for (let i = 0; i < this.assocs.length; i++) {
  const given_assoc = this.assocs[i];
  if (given_assoc.id == id) {
    return given_assoc;
   }
 }
}

private getAuthHeaders() {
const token = localStorage.getItem('token');
const httpHeaders = new HttpHeaders(
  {
    'Content-Type': 'application/json; charset=utf-8',
    'Authorization': 'Token ' + token
  });
  return { headers: httpHeaders };
}

  getAssocs(): void {
  console.log(this.userAssoc.getUserassocs());
  this.userAssoc.getUserassocs().subscribe(assocs => {
    this.assocs = assocs; 
   });
 }

}

userassos.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { Assoc } from '../models/Assoc';

@Injectable()
export class UserassosService {

  httpHeaders = new HttpHeaders({'Content-Type': 'application/json; 
charset=utf-8'});
  baseUrl: string = environment.apiUrl;

  constructor(private http: HttpClient) { }

  getUserassocs(): Observable<any> {
    return this.http.get(this.baseUrl + 'associations/MyAssos/', 
this.getAuthHeaders());
  }

  private getAuthHeaders() {
    const token = localStorage.getItem('token');
    const httpHeaders = new HttpHeaders(
      {'Content-Type': 'application/json; charset=utf-8',
      'Authorization': 'Token ' + token});
    return { headers: httpHeaders};
  }
}

0 个答案:

没有答案