Angular 5.2:使用服务跨越路径的数据持久性

时间:2018-05-02 17:54:51

标签: angular service persistence routerlink

我有一个下拉导航栏,每个选项都有不同的路由器链接。 当用户搜索时,我希望记住搜索类型和搜索过滤器值,并在用户再次导航到搜索选项时显示先前的值。我正在使用服务使搜索类型和搜索过滤器值在整个应用程序中可用,但我无法使其工作。当我导航回搜索时,搜索类型和搜索过滤器值将被初始化。 你能告诉我我错过的东西......

app.component.ts:
-----------------
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Proto Tracking';
}


app.module.ts:
--------------
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { UserSearchComponent } from './components/user-search/user-search.component';
import { UserUpdateComponent } from './components/user-update/user-update.component';
import { UsersService } from './services/users.service';

@NgModule({
  declarations: [
    AppComponent,
    UserSearchComponent,
    UserUpdateComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [ UsersService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

user-search.component.ts:
-------------------------
import { Component, OnInit, Injectable, Directive, OnDestroy } from '@angular/core';
// import User model/interface
import { User } from '../../../app/models/User';
import { UsersService } from '../../../app/services/users.service';


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

@Injectable()

export class UserSearchComponent implements OnInit {

  users: User[];
  searchType: String; searchVal: String;

  constructor(private usersService: UsersService) { 
  }

  ngOnInit() {
    alert("Search component.OnInit");
    alert("Service:" + this.usersService.getSearchType());
    alert("local:" + this.searchType);

    this.searchType = this.usersService.getSearchType();
    this.searchVal = this.usersService.getSearchVal();

  }

  getUsers (searchType: String, searchVal: String) {
    this.usersService.getUsers(this.searchType, this.searchVal).subscribe(users => this.users = users);
    //this.usersService.setSearchType(this.searchType);
    //this.usersService.setSearchVal(this.searchVal);
  }

  ngOnDestroy() {
    alert ("search destroy");
    this.usersService.setSearchType(this.searchType);
    this.usersService.setSearchVal(this.searchVal);
    alert(this.usersService.getSearchType());
  }

}

app-routing.module.ts:
----------------------
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {UserSearchComponent} from "../app/components/user-search/user-search.component";
import {UserUpdateComponent} from "../app/components/user-update/user-update.component";

const routes: Routes = [ 
  {path: 'searchUser', component: UserSearchComponent},
  {path: 'updateUser', component: UserUpdateComponent}
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [RouterModule]
})
export class AppRoutingModule { 

}

app.component.html:
-------------------
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Add user</a>
          <a class="dropdown-item" href="/searchUser">Search user</a>
          <a class="dropdown-item" href="/updateUser">Update user</a>
        </div>

users.service.ts:
-----------------
import { Injectable } from '@angular/core';
import { User } from '../../app/models/User';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }
  )
};

@Injectable()

export class UsersService {

  searchType: String;
  searchVal: String;  
  loginUser: {};
  updUser: User;

  private userSearchUrl = 'http://localhost/ProtoServices/rest/userSearch';
  constructor(private http: HttpClient) {
    alert("Service.Constructor:" + this.searchType);;
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {      
      console.error(error); // log to console instead
      return of(result as T);
    };
  }

  setSearchType(value: String) {
    this.searchType = value;
  }

  getSearchType(): String {
    return this.searchType;
  }

  setSearchVal(value: String) {
    this.searchVal = value;
  }

  getSearchVal(): String {
    return this.searchVal;
  }

  getUsers(searchType: String, searchVal: String): Observable<User[]> {

    this.searchType = searchType;
    this.searchVal = searchVal;
    alert("Service.getUsers:" + this.searchType);
    return this.http.post<User[]>(this.userSearchUrl, { 'searchType': searchType, 'searchVal': searchVal }, httpOptions).pipe(
      catchError(this.handleError('getUsers', []))
    );
  }
}

1 个答案:

答案 0 :(得分:0)

在app.component.html中将href更改为[routerLink&#39;]后,问题得到了解决。

感谢。