用ActivatedRoute获取url中的参数

时间:2022-10-22 13:53:37

突然让我用ActivatedRoute

import {Injectable} from "@angular/core";
import {ActivatedRoute} from "@angular/router";

import {Subscription} from "rxjs/Rx";
import {UserModel} from "./shared/user.model";

@Injectable()
export class UserService {
  protected user: UserModel;
  protected subscription: Subscription;

  constructor(protected activatedRoute: ActivatedRoute) {
    this.subscription = this.activatedRoute.queryParams.subscribe(
      (queryParams: any) => {
        if (queryParams.name) {
          this.setUser(queryParams.name);
        }
      }
    )
  }

  setUser(name) {
    this.user = new UserModel(name);
    console.log('Setting user', this.user);
  }

}