Angular如何在不同视图之间保留user_id

时间:2019-03-15 10:31:45

标签: angular

我有一个用Angular形式包装的表格,我想做的是:用户单击那里选择的产品,并且该产品具有与之关联的id_number,该id_number必须能够在多个查看一次被选择为api的用户是否会基于该数字获取信息?最好为此创建服务吗?然后将该服务注入每个视图?该表的代码为:

html:

    <form [formGroup]="assetForm" (ngSubmit)="onSubmit()">
    <table class="table table-striped table-hover mb-10">
        <thead>
            <tr>
                <th>Number</th>
                <th>Sev</th>
                <th>Phone</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let incident of data">
                <td>
                    <label class="form-radio">
                        <input type="radio" name="id_number" [value]="asset.id_number" formControlName="id_number" <i class="form-icon"></i>{{incident.number}}
                    </label></td>
                <td>{{incident.sev}}</td>
                <td>{{incident.phone}}</td>
            </tr>
        </tbody>
    </table>
    <button class="btn btn-primary" [disabled]="!Form.valid" type="submit">Select</button>
</form>

ts文件:

    ngOnInit() {
    this.assetForm = new FormGroup({
        id_number: new FormControl(''),
    });
}

onSubmit() {
    if (this.assetForm.invalid) {
        this.assetForm.setErrors({
            ...this.assetForm.errors,
            'required': true
        });
        return;
    }
    this.uploading = true;
    this.service.postlist(this.assetForm.value).subscribe((response: any) => {
        console.log(response); //On success response
    }, (errorResponse: any) => {
        console.log(errorResponse); //On unsuccessful response
        this.error = true;
        this.uploading = false;
    });
}

1 个答案:

答案 0 :(得分:1)

最好创建一个服务,然后在其中以及所需的视图/组件中设置值,然后从服务中获取值。如果您使用服务方法,并且在某个时候由于某种原因刷新了页面,则可以简单检查ID是否存在于服务中,并在需要时轻松地重定向到所需的视图。我不建议使用本地存储。

例如,创建一个名为S的服务。您有A,B和C组件。在A组件中,在服务S中设置所需的ID,并且可以在B&C中通过在B&C中注入服务来访问ID值。

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { NgModule } from '@angular/core';
import { AppRoutesModule } from './app.routes';
import { AppComponent } from './app.component';
import { AComponent } from './acomponent.ts';
import { BComponent } from './bcomponent.ts';
import { CComponent } from './ccomponent.ts';
import { CustomService } from './custom.service';

@NgModule({
  declarations: [
    AppComponent,
    AComponent,
    BComponent,
    CComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutesModule,
  ],
  providers: [
   CustomService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

custom.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

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

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

   user_id: any;
   fetchDataURL = "http://localhost:3000/api/some-link";

   // Set data
   setUserId(id) {
       this.user_id = id;
   }

   // Fetch data
   getUserId() {
       return this.user_id;
   }

   // Fetch data which contains "user_id"
   fetchData(): Observable<any> {
       return this._http.get<any>(this.fetchDataURL, httpOptions)
       .pipe(
          retry(1),
          catchError(this.handleError)
       );
   }

   // Error handler - you can customize this accordingly 
   handleError(error) {
     let errorMessage = '';
     if (error.error instanceof ErrorEvent) {
       // client-side error
       errorMessage = `Error: ${error.error.message}`;
     } else {
       // server-side error
       errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
     }
     return throwError(errorMessage);
   }
}

a.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CustomService } from './custom-service-location';

@Component({
  selector: 'component-a',
  templateUrl: './a.component.html'
})

export class AComponent  implements OnInit {

    fetchedData: any;
    constructor(private customService: CustomService) {}

    ngOninit() {
        this.getData();
    }


    // Fetch data
    getData() {
        this.customService.getData()
          .subscribe((data) => {
            console.log(data);
            this.fechedData = data;
            this.customService.setUserId(data.user_id); // Passing the user id to service
          },
          (error) => {
              // logic to handle error accordingly
          });
    }
}

b.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CustomService } from './custom-service-location';

@Component({
  selector: 'component-b',
  templateUrl: './b.component.html'
})

export class BComponent  implements OnInit {

    user_id: any;
    constructor(private customService: CustomService, private router: Router) {}

    ngOninit() {
        this.getData();
    }


    // Fetch user id from service
    getUserData(id) {
        this.customService.getUserId()
          .subscribe((data) => {
            this.user_id = data.user_id;
            if(this.user_id == null) {
                this.router.navigate(['/component-a-route']) // If the id is lost on some page refresh, redirect back to the needed page
            }
          },
          (error) => {
              // logic to handle error accordingly
          });
    }


    someOtherFunction() {
      // some other function with some other logic
    }
}

正如您在上面看到的那样,有一个主要的“应用程序”模块,两个部分a和b和一个服务文件。在组件A中,调用函数fetchData并在其中返回“ user_id”(假设),然后使用“ setUserId()”方法在自定义服务中设置user_id,然后就可以使用“ getUserId”在组件b中获取它。 ()”方法。

我希望以上内容能使事情变得清楚并且有帮助。