1

我是 Angular 4 的新手,在不使用 AcitvatedRoute 的情况下单击按钮时将数据从一个组件传递到另一个组件时卡住了(没有在 URL 中传递数据)

我的 searchOption.component.html 包含提交按钮的以下代码:

<td><a routerLink="searchDetails"> <button id="testButton"  (click)="sendVal()">Submit</button></a></td>

我的 searchOption.component.ts 存储以下代码:

sendVal() {
  this.selectedAcc = this.signUpForm.form.value.accNo;
  console.log("Account Lists3::"+this.selectedAcc);
  this.router.navigate(['./searchDetails', this.selectedAcc])
}

我的要求是单击按钮将 this.selectedAcc 传递给另一个组件 searchDetails.component.ts 。

4

1 回答 1

-1

我之前回答过类似的问题,相信你会在这里找到答案。Angular 2 发送数组另一页

这是答案的有用部分。

export class WeatherService {

  weatherClass: Weather;
  
  //BehaviorSubject can store the last value given until the service destroyed or otherwise changed
  private data: BehaviorSubject<Weather> = new BehaviorSubject(null);

  constructor(private http: Http) {}

  otherWeather(city: string) {
    return this.http.get(`http://api.openweathermap.org/data/2.5/weather?appid=0f3fb9fa31ad3d41f1bb2bd0841c3f2f&q=${city}&units=imperial&cnt=10`).map((response: Response) => response.json());
  }
  
  setData(value: Weather) {
    this.data.next(value);
  }
  
  getData(): Observable<Weather> {
    return this.data.asObservable();
  }
}

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

export class ParentComponet implements OnInit {

  parentData: Type = ["ADANA", "ADIYAMAN", "AFYONKARAHİSAR", "AĞRI", "AMASYA", "ANKARA", "ANTALYA", "ARTVİN"];;

  constructor(private service: WeatherService, private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
   this.service.otherWeather(this.value.text).subscribe( (data: Weather) => { 
    this.service.setData(data);
    });
  }

}


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

export class ChildComponet implements OnInit {

  childData: Weather;

  constructor(private service: WeatherService, private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.service.getData.subscribe((vales: Weather) => {
      this.childData = vales;
    });
  }

}

使用这种方法,您会注意到数据不会立即返回,并且代码不会等待数据。您必须执行与subscribe()块中数据相关的任何 TypeScript 逻辑才能使其工作。HTML 将在值更改时自行更新。当 BehaviorSubject 的值发生变化时使用该方法,任何订阅该getData()方法的地方也将接收到新数据。

于 2017-09-28T12:26:09.550 回答