Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Angular 2中保存服务内的数据_Javascript_Angularjs_Frontend - Fatal编程技术网

Javascript 在Angular 2中保存服务内的数据

Javascript 在Angular 2中保存服务内的数据,javascript,angularjs,frontend,Javascript,Angularjs,Frontend,我正在使用一个服务,当用户输入文本框时,从api中提取数据。在用户单击项目的详细信息页面之前,一切都很正常。应用程序路由到该项目,然后按下应用程序中的“后退”按钮后,用户的输入不会保存,输入和电影列表组件为空 问题:我正在寻找保存此输入的Angular 2方法,这样当用户返回到电影列表时,数据就在那里,用于他们以前的搜索查询 用户在这里输入他们的电影标题,在用户停止键入后,从电影服务返回一个可观察的内容 搜索文本框.component.ts import { Component, OnInit

我正在使用一个服务,当用户输入文本框时,从api中提取数据。在用户单击项目的详细信息页面之前,一切都很正常。应用程序路由到该项目,然后按下应用程序中的“后退”按钮后,用户的输入不会保存,输入和电影列表组件为空

问题:我正在寻找保存此输入的Angular 2方法,这样当用户返回到电影列表时,数据就在那里,用于他们以前的搜索查询

用户在这里输入他们的电影标题,在用户停止键入后,从电影服务返回一个可观察的内容

搜索文本框.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MovieService } from '../movie.service';
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'app-search-textbox',
  templateUrl: './search-textbox.component.html',
  styleUrls: ['./search-textbox.component.scss'],
  providers: [MovieService]
})
export class SearchTextboxComponent implements OnInit {

  private movies;
  private title = new FormControl();

  constructor(private movieService: MovieService) {
    this.title.valueChanges
             .debounceTime(400)
             .distinctUntilChanged()
             .flatMap(title => this.movieService.getMovies(title))
             .subscribe(movies => this.movies = movies);
  }

  ngOnInit() {}

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

import { MovieService } from '../movie.service';

@Component({
  selector: 'app-movie-list',
  templateUrl: './movie-list.component.html',
  styleUrls: ['./movie-list.component.scss'],
  providers: [MovieService]
})
export class MovieListComponent implements OnInit {
  @Input() movies: Object[];

  constructor(
    private router: Router,
    private movieService: MovieService
  ) {}

  ngOnInit() {}

  gotoDetail(selectedMovieID): void {
    this.router.navigate(['./detail', selectedMovieID])
  }
}
import { Component, OnInit } from '@angular/core';
import { MovieService } from '../movie.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-movie-detail',
  templateUrl: './movie-detail.component.html',
  styleUrls: ['./movie-detail.component.scss'],
  providers: [MovieService]
})

export class MovieDetailComponent implements OnInit {
  private movie: Object;

  constructor(
    private movieService: MovieService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  ngOnInit() {
    this.route.params
        .switchMap((params: Params) => this.movieService.getMovieDetails(params['id']))
        .subscribe((movie: Object) => this.movie = movie)
  }

  goBack(): void {
    this.location.back();
  }

}
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class MovieService {

  constructor (private http: Http) {}

  private moviesUrl = 'http://omdbapi.com?s=';
  private movieDetailsUrl = 'http://omdbapi.com?i=';

  getMovies(searchInput: string) : Observable<Object[]>{
    return this.http.get(this.moviesUrl + searchInput)
                    .map((res:Response) => res.json().Search)
                    .catch((error:any) => Observable.throw(error.json().error || 'error'));
  }

  getMovieDetails(movieID: string) : Observable<Object> {
    return this.http.get(this.movieDetailsUrl + movieID + '&tomatoes=true') // add rotten tomatoes param
                    .map((r: Response) => r.json())
                    .catch((error:any) => Observable.throw(error.json().error || 'error'));
  }

}
搜索textbox.component.html

<div class="row searchbox">
  <div class="col-md-12">
    <input type="text" [formControl]="title" placeholder="Enter Title" autofocus/>
  </div>
</div>
<div class="row" [class.loading]="!movies && title.value ">
  <app-movie-list [movies]="movies"></app-movie-list>
</div>
<div *ngFor="let movie of movies">
  <div *ngIf="movie.Poster != 'N/A'"
       class="col-lg-3 col-md-4 col-sm-6 col-xs-12">
     <div class="card">
       <img class="card-img-top" [src]="movie.Poster" alt="Card image cap">
       <div class="card-block">
         <h4 class="card-title">{{movie.Title}}</h4>
         <p class="card-text">{{movie.Year}}</p>
         <button (click)="gotoDetail(movie.imdbID)" class="btn btn-success">Details</button>
       </div>
     </div>
  </div>
</div>
<div *ngIf="movie">
  <div class="row">
    <div class="col-md-6">
      <img [src]="movie.Poster" />
    </div>
    <div class="col-md-6 movie-details">
      <h1>{{movie.Title}}: {{movie.Year}}</h1>
      <div *ngIf="movie.tomatoMeter != 'N/A'">
        <progress class="progress progress-striped progress-success" [class.progress-danger]="movie.tomatoMeter < 50" value="{{movie.tomatoMeter}}" max="100"></progress>
        <h1>{{movie.tomatoMeter}}%</h1>
        <div class="consensus">
          <p>{{movie.tomatoConsensus}}</p>
        </div>
      </div>
    </div>
  </div>
  <button (click)="goBack()" class="btn btn-info">Go Back</button>
</div>
电影列表.component.html

<div class="row searchbox">
  <div class="col-md-12">
    <input type="text" [formControl]="title" placeholder="Enter Title" autofocus/>
  </div>
</div>
<div class="row" [class.loading]="!movies && title.value ">
  <app-movie-list [movies]="movies"></app-movie-list>
</div>
<div *ngFor="let movie of movies">
  <div *ngIf="movie.Poster != 'N/A'"
       class="col-lg-3 col-md-4 col-sm-6 col-xs-12">
     <div class="card">
       <img class="card-img-top" [src]="movie.Poster" alt="Card image cap">
       <div class="card-block">
         <h4 class="card-title">{{movie.Title}}</h4>
         <p class="card-text">{{movie.Year}}</p>
         <button (click)="gotoDetail(movie.imdbID)" class="btn btn-success">Details</button>
       </div>
     </div>
  </div>
</div>
<div *ngIf="movie">
  <div class="row">
    <div class="col-md-6">
      <img [src]="movie.Poster" />
    </div>
    <div class="col-md-6 movie-details">
      <h1>{{movie.Title}}: {{movie.Year}}</h1>
      <div *ngIf="movie.tomatoMeter != 'N/A'">
        <progress class="progress progress-striped progress-success" [class.progress-danger]="movie.tomatoMeter < 50" value="{{movie.tomatoMeter}}" max="100"></progress>
        <h1>{{movie.tomatoMeter}}%</h1>
        <div class="consensus">
          <p>{{movie.tomatoConsensus}}</p>
        </div>
      </div>
    </div>
  </div>
  <button (click)="goBack()" class="btn btn-info">Go Back</button>
</div>
电影细节.component.html

<div class="row searchbox">
  <div class="col-md-12">
    <input type="text" [formControl]="title" placeholder="Enter Title" autofocus/>
  </div>
</div>
<div class="row" [class.loading]="!movies && title.value ">
  <app-movie-list [movies]="movies"></app-movie-list>
</div>
<div *ngFor="let movie of movies">
  <div *ngIf="movie.Poster != 'N/A'"
       class="col-lg-3 col-md-4 col-sm-6 col-xs-12">
     <div class="card">
       <img class="card-img-top" [src]="movie.Poster" alt="Card image cap">
       <div class="card-block">
         <h4 class="card-title">{{movie.Title}}</h4>
         <p class="card-text">{{movie.Year}}</p>
         <button (click)="gotoDetail(movie.imdbID)" class="btn btn-success">Details</button>
       </div>
     </div>
  </div>
</div>
<div *ngIf="movie">
  <div class="row">
    <div class="col-md-6">
      <img [src]="movie.Poster" />
    </div>
    <div class="col-md-6 movie-details">
      <h1>{{movie.Title}}: {{movie.Year}}</h1>
      <div *ngIf="movie.tomatoMeter != 'N/A'">
        <progress class="progress progress-striped progress-success" [class.progress-danger]="movie.tomatoMeter < 50" value="{{movie.tomatoMeter}}" max="100"></progress>
        <h1>{{movie.tomatoMeter}}%</h1>
        <div class="consensus">
          <p>{{movie.tomatoConsensus}}</p>
        </div>
      </div>
    </div>
  </div>
  <button (click)="goBack()" class="btn btn-info">Go Back</button>
</div>

{{movie.Title}:{{movie.Year}
{{movie.tomotometer}}%
{{movie.tomatoConsensus}}

回去
电影服务.ts

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MovieService } from '../movie.service';
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'app-search-textbox',
  templateUrl: './search-textbox.component.html',
  styleUrls: ['./search-textbox.component.scss'],
  providers: [MovieService]
})
export class SearchTextboxComponent implements OnInit {

  private movies;
  private title = new FormControl();

  constructor(private movieService: MovieService) {
    this.title.valueChanges
             .debounceTime(400)
             .distinctUntilChanged()
             .flatMap(title => this.movieService.getMovies(title))
             .subscribe(movies => this.movies = movies);
  }

  ngOnInit() {}

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

import { MovieService } from '../movie.service';

@Component({
  selector: 'app-movie-list',
  templateUrl: './movie-list.component.html',
  styleUrls: ['./movie-list.component.scss'],
  providers: [MovieService]
})
export class MovieListComponent implements OnInit {
  @Input() movies: Object[];

  constructor(
    private router: Router,
    private movieService: MovieService
  ) {}

  ngOnInit() {}

  gotoDetail(selectedMovieID): void {
    this.router.navigate(['./detail', selectedMovieID])
  }
}
import { Component, OnInit } from '@angular/core';
import { MovieService } from '../movie.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-movie-detail',
  templateUrl: './movie-detail.component.html',
  styleUrls: ['./movie-detail.component.scss'],
  providers: [MovieService]
})

export class MovieDetailComponent implements OnInit {
  private movie: Object;

  constructor(
    private movieService: MovieService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  ngOnInit() {
    this.route.params
        .switchMap((params: Params) => this.movieService.getMovieDetails(params['id']))
        .subscribe((movie: Object) => this.movie = movie)
  }

  goBack(): void {
    this.location.back();
  }

}
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class MovieService {

  constructor (private http: Http) {}

  private moviesUrl = 'http://omdbapi.com?s=';
  private movieDetailsUrl = 'http://omdbapi.com?i=';

  getMovies(searchInput: string) : Observable<Object[]>{
    return this.http.get(this.moviesUrl + searchInput)
                    .map((res:Response) => res.json().Search)
                    .catch((error:any) => Observable.throw(error.json().error || 'error'));
  }

  getMovieDetails(movieID: string) : Observable<Object> {
    return this.http.get(this.movieDetailsUrl + movieID + '&tomatoes=true') // add rotten tomatoes param
                    .map((r: Response) => r.json())
                    .catch((error:any) => Observable.throw(error.json().error || 'error'));
  }

}
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http,Response,Headers,RequestOptions};
从'rxjs/Rx'导入{Observable};
@可注射()
导出类电影服务{
构造函数(私有http:http){}
私人电影http://omdbapi.com?s=';
私人电影http://omdbapi.com?i=';
getMovies(searchInput:string):可观察{
返回this.http.get(this.moviesUrl+searchInput)
.map((res:Response)=>res.json().Search)
.catch((error:any)=>Observable.throw(error.json().error | |“error”);
}
getMovieDetails(movieID:string):可观察{
返回this.http.get(this.movieDetailsUrl+movieID+'&thoods=true')//添加烂番茄参数
.map((r:Response)=>r.json()
.catch((error:any)=>Observable.throw(error.json().error | |“error”);
}
}

在路线加载时,参数不会保留

您需要将它们临时存储在会话存储/位置存储中

  • 在列表页路由的CanDeActivate()上,将它们存储在位置/会话存储中
  • 在SearchTextboxComponent中的ngOnInit()方法上,从存储器中读取并将其绑定到模板中